package com.letu.android.widget;

import android.app.Activity;
//import android.app.Activity.OnTitleIconClickListener;
import android.app.AlertDialog;
//import android.app.BottomTabActivity;
import android.app.TabActivity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import android.widget.ViewFlipper;


import android.view.Gravity;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.animation.AnimationUtils;
import android.view.MotionEvent;
import android.webkit.WebView;
import android.widget.AbsListView;
//import android.widget.BottomTabHost;
import android.widget.TabHost;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.Toast;

import android.view.View.OnTouchListener;
import dalvik.system.VMRuntime;
import java.io.InputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import org.json.JSONObject;


//public class SearchActivity extends TabActivity implements TabHost.OnTabChangeListener {
//public class SearchActivity extends BottomTabActivity implements 
public class SearchActivity extends TabActivity implements 
	//BottomTabHost.OnTabChangeListener,
	TabHost.OnTabChangeListener
	{

	// Scene page
	private static final int LIST_SEARCH_RESULT_COUNT = 10;
	private static final int LIST_TOTAL_REQUEST_COUNT = 50;
	private static final int SCENE_VIEW_COUNT = 3;
	private static final int SCENE_CONTENT_VIEW_COUNT = 5;
	private static final int SCENE_CONTENT_TAB_COUNT = 3;
	
	private static final int DIALOG_MONTH_SCENE_LIST = 0;
	private static final int DIALOG_RECOMMEND_SCENE_LIST = DIALOG_MONTH_SCENE_LIST + 1;
	private static final int DIALOG_AROUND_SCENE_LIST = DIALOG_RECOMMEND_SCENE_LIST + 1;
	private static final int DIALOG_LOADING = DIALOG_AROUND_SCENE_LIST + 1;
	
	private static final int SCENE_AREA_LIST_SOURCE_SEARCH = 1;
	private static final int SCENE_AREA_LIST_SOURCE_AROUND = 2;
	private static final int SCENE_AREA_LIST_SOURCE_MONTH = 3;
	
	private static final String NULL = "null";
	
	private View mSceneViews[] = new View[SCENE_VIEW_COUNT];
	private View mSceneContentViews[] = new View[SCENE_CONTENT_VIEW_COUNT];
	private Button mScenePageTabButton[] = new Button[SCENE_CONTENT_TAB_COUNT];

	private int mCurrentSceneOperationViewIndex = 0;
	private int mCurrentSceneContentViewIndex = 0;
	private int mCurrentSceneContentViewTab0Index = SCENE_ID; // 景区详情 {0, 4}
	private int mCurrentSceneContentViewTab2Index = NOTE_ID; // 游记攻略 {2, 3}

	private static boolean mShortcut = false;

	private static final int SCENE = 0;
	private static final int ROUTE = SCENE + 1;
	private static final int NOTE = ROUTE + 1;

	private static final int SEARCH_ID = 0;
	private static final int RESULT_ID = SEARCH_ID + 1;
	private static final int SCENE_MAIN_ID = RESULT_ID + 1;

	private static final int SCENE_ID = 0;
	private static final int ROUTE_ID = SCENE_ID + 1;
	private static final int NOTE_ID = ROUTE_ID + 1;
	private static final int NOTE_CONTENT_ID = NOTE_ID + 1;
	private static final int SCENE_SPOT_ID = NOTE_CONTENT_ID + 1;
	
	private static final int SCENE_BUTTON = 0;
	private static final int ROUTE_BUTTON = SCENE_BUTTON + 1;
	private static final int NOTE_BUTTON = ROUTE_BUTTON + 1;
	
	private Database mDatabase = new Database(this);
	private String mSearchCityId;

	private static final int HOTLINE_LIST_PAGE = 0;
	private static final int HOTLINE_CONTENT_PAGE = 1;
	private static final int HOTLINE_PAGE_COUNT = 2;
	
	private int mHotLineCurrentPageIndex = HOTLINE_LIST_PAGE;
	private View mHotLinePages[] = new View[HOTLINE_PAGE_COUNT];

	private String[][] mHotLineListContent = new String[2][];

	private String mHotLineContentContentTitle;
	private String mHotLineContentContentID;
	private String mHotLineContentContent;

	private static final String DATA_HOTLINE_CURRENT_PAGE_INDEX = "mHotLineCurrentPageIndex";
	private static final String DATA_HOTLINE_LIST_ID = "mListIDs";
	private static final String DATA_HOTLINE_LIST_TITLE = "mListTitles";
	private static final String DATA_HOTLINE_CONTENT_ID = "mContentID";
	private static final String DATA_HOTLINE_CONTENT_TITLE = "mContentTitle";
	private static final String DATA_HOTLINE_CONTENT_CONTENT = "mHotLineContentContent";

	private void showSceneView(int index) {
		for (int i = 0; i < mSceneViews.length; i++) {
			mSceneViews[i].setVisibility(View.GONE);
		}
		mSceneViews[index].setVisibility(View.VISIBLE);
	}

	private void showSceneContentView(int index) {
		for (int i = 0; i < mSceneContentViews.length; i++) {
			mSceneContentViews[i].setVisibility(View.GONE);
		}
		mSceneContentViews[index].setVisibility(View.VISIBLE);
	}
	
	private void setmScenePageTabButtonBgColor(int index) {
		int count = mScenePageTabButton.length;
		for (int i = 0; i < count; i++) {
			mScenePageTabButton[i].setBackgroundColor(0xFF909090);
		}
		mScenePageTabButton[index].setBackgroundColor(0xFF009090);
	}

	//scene content
	private int mSceneAreaSearchResultCount;
	private String[][] mSceneAreaSearchResultList = new String[2][];
	private String[][] mMonthRecommendContent = new String[2][];
	private String[][] mScenePageRecommendContent = new String[2][];
	private String[][] mScenePageAroundContent = new String[2][];
	private String[] mRouteAccommodationContent;
		
	private String   mSceneAreaId;
	private String[] mSceneAreaDetail;

	private String[] mNoteListTypes;
	private String[] mNoteListTitles;
	private String[] mNoteListIDs;

	private String mNoteContentTitle;
	private String mNoteContentContent;
	private String mNoteContentAuthor;
	private String mNoteContentID;
	private String mNoteContentType;

	private ImageButton mSearchResultPrePage; 
	private ImageButton mSearchResultNextPage;
	private int mSearchResultCurrentPage = 0;

	//Tab related data
	private static final String tab1 = "tab1";
	private static final String tab2 = "tab2";
	private static final String tab3 = "tab3";
	private static final String tab4 = "tab4";
	
	private void addTabs() {
		//BottomTabHost tabHost = getTabHost();
		TabHost tabHost = getTabHost();

		LayoutInflater.from(this).inflate(R.layout.main,
				tabHost.getTabContentView(), true);

		//BottomTabHost.TabSpec tabSpec;
		TabHost.TabSpec tabSpec;
		tabSpec = tabHost.newTabSpec(tab1).setIndicator(
				getString(R.string.tab_1)).setContent(R.id.search_id);
		tabHost.addTab(tabSpec);

		tabSpec = tabHost.newTabSpec(tab2).setIndicator(
				getString(R.string.tab_2)).setContent(R.id.hotline_id);
		tabHost.addTab(tabSpec);

		tabSpec = tabHost.newTabSpec(tab3).setIndicator(
				getString(R.string.tab_3)).setContent(R.id.collection_page_id);
		tabHost.addTab(tabSpec);

		tabHost.addTab(tabHost.newTabSpec(tab4).setIndicator(
				getString(R.string.tab_4)).setContent(R.id.about_id));

		tabHost.setOnTabChangedListener(this);
	}

	public void onTabChanged(String tabId) {
		hideAllViews();
		if (tabId.equals(tab1)) {
			displayScenePage();
		} else if (tabId.equals(tab2)) {
			/*mHotLineListContent[1] == null means when application first time
			 * started, we need to get data from network. 
			 * later we won't down load data */
			if (mHotLineListContent[1] == null) {
				loadHotLinePage();
			}
			displayHotLinePage();
		} else if (tabId.equals(tab3)) {
			displayCollectionListPage();
		} else if (tabId.equals(tab4)) {
			displayAboutPage();
		}
		changeTitleIconAsHomePage();
	}

	private void initPreNextPageButtons() {
		mSearchResultPrePage = (ImageButton) findViewById(R.id.search_pre_page_id);
		mSearchResultNextPage = (ImageButton) findViewById(R.id.search_next_page_id);
		
		mRoutePrePage = (ImageButton) findViewById(R.id.route_pre_page_id);
		mRouteNextPage = (ImageButton) findViewById(R.id.route_next_page_id);
		
		mNoteListPrePage = (ImageButton) findViewById(R.id.note_list_pre_page_id);
		mNoteListNextPage = (ImageButton) findViewById(R.id.note_list_next_page_id);
	}
	
	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		addTabs();
		
		initPreNextPageButtons();
		
		loadMonthRecommendFlipperContent();	
		loadSceneMainPage();
		loadSearchConditionPage(bundle);
		loadSearchResultPage();
		
		initHotLinePage();
		loadCollectionPage(bundle);

		if (bundle == null) {
			setCurrentSceneOperationView(SEARCH_ID);			
			//customTitleIcon(R.drawable.exit_pressed, R.drawable.exit_released, 
			//		R.string.exit_title, this);
		} else {
			restoreSearchResultList(bundle);
			restoreSceneArea(bundle);
			restoreSceneSpot(bundle);
			restoreRouteAccommodation(bundle);
			restoreNoteList(bundle);
			restoreNoteContent(bundle);
			
			restoreHotLinePage(bundle);

			mCurrentSceneOperationViewIndex = bundle.getInt(DATA_CURRENT_SCENE_OPERATION_VIEW_INDEX);
			mCurrentSceneContentViewTab0Index = bundle.getInt(DATA_CURRENT_SCENE_CONTENT_VIEW_TAB0_INDEX);
			mCurrentSceneContentViewTab2Index = bundle.getInt(DATA_CURRENT_SCENE_CONTENT_VIEW_TAB2_INDEX);
			mCurrentSceneContentViewIndex = bundle.getInt(DATA_CURRENT_SCENE_CONTENT_VIEW_INDEX);

			setCurrentSceneOperationView(mCurrentSceneOperationViewIndex);
			if (mCurrentSceneOperationViewIndex == SCENE_MAIN_ID) {
				switch (mCurrentSceneContentViewIndex) {
					case SCENE_ID:
						setmScenePageTabButtonBgColor(SCENE_BUTTON);
						break;
					case ROUTE_ID:
						setmScenePageTabButtonBgColor(ROUTE_BUTTON);
						break;
					case NOTE_ID:
						setmScenePageTabButtonBgColor(NOTE_BUTTON);
						break;
					case NOTE_CONTENT_ID:
						setmScenePageTabButtonBgColor(NOTE_BUTTON);
						break;
					case SCENE_SPOT_ID:
						setmScenePageTabButtonBgColor(SCENE_BUTTON);
						break;
				}
				Log.d("_________", mCurrentSceneContentViewIndex+"   huanghun");
				showSceneContentView(mCurrentSceneContentViewIndex);
			}			
			getTabHost().setCurrentTab(bundle.getInt(DATA_CURRENT_TAB_INDEX));
			changeTitleIconAsHomePage();
		}
	}

	/*
	 * 用三个Button模拟Tab效果
	 */
	private void loadSceneMainPage() {
		// 3 TAB BUTTON
		Button sceneButton = (Button) findViewById(R.id.scene_button_id);
		sceneButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				setmScenePageTabButtonBgColor(SCENE_BUTTON);
				setCurrentSceneContentView(mCurrentSceneContentViewTab0Index);
			}
		});

		Button recommendButton = (Button) findViewById(R.id.recommend_button_id);
		recommendButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				setmScenePageTabButtonBgColor(ROUTE_BUTTON);
				setCurrentSceneContentView(ROUTE_ID);
			}
		});

		Button noteButton = (Button) findViewById(R.id.note_button_id);
		noteButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				setmScenePageTabButtonBgColor(NOTE_BUTTON);
				setCurrentSceneContentView(mCurrentSceneContentViewTab2Index);
			}
		});
		
		mScenePageTabButton[0] = sceneButton;
		mScenePageTabButton[1] = recommendButton;
		mScenePageTabButton[2] = noteButton;

		showSelectedTabButton();
	}
	
	/*
	 * 首页: 选择省自动列出城市， 点击确定后进入搜索结果页面
	 */	
	private void loadSearchConditionPage(Bundle inState) {
		final Spinner provinces = (Spinner) findViewById(R.id.provinces);
		ArrayAdapter<String> adapterProvince = new ArrayAdapter<String>(this,
			android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.province_name));
		adapterProvince.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		provinces.setAdapter(adapterProvince);
		int provinceIndex = 0;
		if (inState != null) {
			provinceIndex = inState.getInt(DATA_SPINNER_PROVINCE_INDEX);
			provinces.setSelection(provinceIndex);
		}

		provinces.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				Spinner s = (Spinner) findViewById(R.id.cities);
				String provinceIds[] = getResources().getStringArray(R.array.province_id);
				mSearchCityId = provinceIds[position];
				ArrayAdapter<String> adapter = new ArrayAdapter<String>(SearchActivity.this,
					android.R.layout.simple_spinner_item, getCityNameAndId(mSearchCityId)[1]);
				adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);				
				s.setAdapter(adapter);
			}
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});
		
        //-------------------------------------------------------
		
		String cityProvinceId = getResources().getStringArray(R.array.province_id)[1];
		Spinner cities = (Spinner) findViewById(R.id.cities);
		String cityValue[] = getCityNameAndId(cityProvinceId)[1];

		ArrayAdapter<String> adapterCities = new ArrayAdapter<String>(this,
			android.R.layout.simple_spinner_item, cityValue);		
		adapterCities.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		cities.setAdapter(adapterCities);
		
		int cityIndex = 0;
		cities.setSelection(cityIndex);
		if (inState != null) {
			cityIndex = inState.getInt(DATA_SPINNER_CITIES_INDEX);
			cities.setSelection(cityIndex);
		}
		
		cities.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				int provinceIndex = provinces.getSelectedItemPosition();
				if (provinceIndex ==0 ) {
					Toast.makeText(SearchActivity.this, getResources().getString(R.string.error_input_without_province_key), Toast.LENGTH_SHORT).show();
					return true;
				}
				return false;
			}
		});

		mSceneViews[SEARCH_ID] = (View) findViewById(R.id.search_id);
		mSceneViews[RESULT_ID] = (View) findViewById(R.id.result_id);
		mSceneViews[SCENE_MAIN_ID] = (View) findViewById(R.id.scene_main_id);

		mSceneContentViews[SCENE_ID] = (View) findViewById(R.id.scene_id);
		mSceneContentViews[ROUTE_ID] = (View) findViewById(R.id.route_id);
		mSceneContentViews[NOTE_ID] = (View) findViewById(R.id.note_id);
		mSceneContentViews[NOTE_CONTENT_ID] = (View) findViewById(R.id.note_content_id);
		mSceneContentViews[SCENE_SPOT_ID] = (View) findViewById(R.id.scene_spot_id);

		Button searchButton = (Button) findViewById(R.id.search_button_id);
		searchButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {				
				mSearchResultCurrentPage = 0;
				String url = createSearchRequestUrl();
				if (url == null) {
					return;
				}
				loadSearchResultList(url);
			}
		});
	}

	private static final String DATA_SPINNER_PROVINCE_INDEX = "DATA_SPINNER_PROVINCE_INDEX";
	private static final String DATA_SPINNER_CITIES_INDEX = "DATA_SPINNER_CITIES_INDEX";

	private void saveSearchConditionPage(Bundle outState) {
		Spinner provinces = (Spinner) findViewById(R.id.provinces);
		Spinner cities = (Spinner) findViewById(R.id.cities);
		
		outState.putInt(DATA_SPINNER_PROVINCE_INDEX, provinces.getSelectedItemPosition());
		outState.putInt(DATA_SPINNER_CITIES_INDEX, cities.getSelectedItemPosition());
	}
	
	private void showScenePageTabButtons(int index) {
		int count = mScenePageTabButton.length;
		for (int i = 0; i < count; i++) {
			mScenePageTabButton[i].setVisibility(View.VISIBLE);
		}
		setmScenePageTabButtonBgColor(index);
	}

	private void loadSearchResultPage() {
		final ListView listView = (ListView) mSceneViews[RESULT_ID]
				.findViewById(R.id.search_result_list_id);
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				setCurrentSceneOperationView(SCENE_MAIN_ID);
				
				setmScenePageTabButtonBgColor(SCENE_BUTTON);

				setCurrentSceneContentView(SCENE_ID);
				mCurrentSceneContentViewTab0Index = SCENE_ID;
				
				loadSceneArea(position, SCENE_AREA_LIST_SOURCE_SEARCH);
			}
		});	
		/*
		 * 上下翻页按钮
		 */
		mSearchResultPrePage.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				--mSearchResultCurrentPage;
				String url = createSearchRequestUrl();
				loadSearchResultList(url);
			}
		});
		mSearchResultNextPage.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				++mSearchResultCurrentPage;
				String url = createSearchRequestUrl();
				loadSearchResultList(url);
			}
		});
	}

	private static final String BASE_URL = "http://nokia.hz.lotour.com/";
	private static final String PREFIX_SEARCH_KEY = "ScenicListForLenovo.ashx?key=";
	private static final String PREFIX_CITY_ID = "&cid=";
	private static final String PREFIX_ROW_INDEX = "&rowindex=";
	private static final String PREFIX_REQUEST_COUNT = "&n=";
	private static final String PREFIX_CALLBACK = "&callback=?";

	/*
	 * 根据搜索条件构造请求url
	 */
	private String createSearchRequestUrl() {
		final EditText editText = (EditText) findViewById(R.id.search_edit);

		String searchKey = null;
		String key = editText.getText().toString().trim();
		if (key == null || key.length() == 0) {
			searchKey = "";
		} else {			
			searchKey = Uri.encode(key);
		}
		
		Spinner cities = (Spinner) findViewById(R.id.cities);
		int cityIndex = cities.getSelectedItemPosition();
		Spinner provinces = (Spinner) findViewById(R.id.provinces);
		int provinceIndex = provinces.getSelectedItemPosition();		

		if (provinceIndex ==0 && cityIndex == 0 && searchKey.equals("")) {
			Toast.makeText(this, getResources().getString(R.string.error_input_key), Toast.LENGTH_SHORT).show();	
			return null;
		}
		String cid = getCityNameAndId(mSearchCityId)[0][cityIndex];
		int rowIndex = mSearchResultCurrentPage * LIST_SEARCH_RESULT_COUNT;
		int count = LIST_SEARCH_RESULT_COUNT;
		String url = createSearchRequestUrl(searchKey, cid, rowIndex, count);
		return url;
	}

	private static String createSearchRequestUrl(String key, String cid, int rowIndex, int count) {
		return BASE_URL + PREFIX_SEARCH_KEY + key + 
			PREFIX_CITY_ID + cid + PREFIX_ROW_INDEX + 
			rowIndex + PREFIX_REQUEST_COUNT + count + PREFIX_CALLBACK;
	}

	private AsyncTask<String, Void, Boolean> mLoadingTask;
	
	/*
	 * 从网络上获得数据，然后显示； 因为此时显示的不再是首页， 将退出按钮改为返回首页按钮
	 */
	private Handler mSearchResultListHandler;
	private static final int MSG_SEARCH_RESULT = 0;
	private static final String KEY_MSG_SEARCH_RESULT = "key_msg_search_result";	
		
	private void loadSearchResultList(String url) {
		//String url = "http://nokia.hz.lotour.com/ScenicListForLenovo.ashx?key=%E5%8C%97&cid=13&rowindex=0&n=10&callback=?";
		//url = "http://nokia.hz.lotour.com/ScenicListForLenovo.ashx?key=%E5%8C%97&cid=13&rowindex=0&n=10&callback=?";		
		mSearchResultListHandler = new Handler() {
			public void handleMessage(Message msg) {
				switch(msg.what) {
				case MSG_SEARCH_RESULT:
					String objStr = msg.getData().getString(KEY_MSG_SEARCH_RESULT);
					JSONObject obj = HttpUtil.getJSONObject(objStr);
					ListView listView = (ListView) mSceneViews[RESULT_ID]
					                               			.findViewById(R.id.search_result_list_id);
					mSceneAreaSearchResultList = HttpUtil.parseSearchResult(obj);
					mSceneAreaSearchResultCount = HttpUtil.parseSearchResultCount(obj);
					int number = mSceneAreaSearchResultCount;
					String mainContent = getResources().getString(R.string.search_result_title);
					TextView tv = (TextView) findViewById(R.id.search_condition_id);
					setTurnPageButtonVisibility(tv, mainContent, number, mSearchResultCurrentPage * LIST_SEARCH_RESULT_COUNT, 
						mSearchResultPrePage, mSearchResultNextPage);

					if (mSceneAreaSearchResultList != null && 
							mSceneAreaSearchResultList[1] != null)
						listView.setAdapter(new ArrayAdapter<String>(SearchActivity.this, 
								android.R.layout.simple_list_item_1, mSceneAreaSearchResultList[1]));
					else
						listView.setAdapter(null);
					
					setCurrentSceneOperationView(RESULT_ID);
					changeTitleIconAsHomePage();
					break;
				}
			}
		};
		
        int msgTypes[] = {MSG_SEARCH_RESULT};
        String msgKeys[] = {KEY_MSG_SEARCH_RESULT};
		mLoadingTask = new DataLoadingTask(mSearchResultListHandler, msgTypes, msgKeys).execute(url);		
	}
	
	/*
	 * 从网络上获得数据的任务， 显示等待对话框；
	 * 获取数据后发送获得的数据到UI线程， 并删除等待对话框
	 */
	
    class DataLoadingTask extends AsyncTask<String, Void, Boolean> {
        private Handler mHandler;
        private int[] mMsgTypes;
        private String[] mMsgKeys;

        DataLoadingTask(Handler handler, int[] msgTypes, String[] msgKeys) {
        	mMsgTypes = msgTypes;
        	mMsgKeys = msgKeys;
        	mHandler = handler;
        }

		protected void onPreExecute() {
			showDialog(DIALOG_LOADING);
		}

        protected Boolean doInBackground(String... params) {
        	for (int i = 0; i < params.length; i++) {
        		String url = params[i];
        		String data = HttpUtil.getResponseString(url);
        		if (data == null)
        			return false;
        		sendDownloadData(data, mMsgTypes[i], mMsgKeys[i]);
        	}
            return true;
        }

        private void sendDownloadData(String data, int msgType, String msgKey) {
        	Message msg = Message.obtain();
            Bundle b = new Bundle();
            msg.what = msgType;            
            b.putString(msgKey, data);
            msg.setData(b);
            mHandler.sendMessage(msg);
        }
        
        protected void onPostExecute(Boolean result) {
            if (!isCancelled()) {
				if (result) {				
				} else {
					Toast.makeText(SearchActivity.this, getResources().getString(R.string.error_network), Toast.LENGTH_SHORT).show();
				}
            } else {
            	if (getStatus() == AsyncTask.Status.RUNNING)
            		cancel(true);
            }
            //dismissDialog(DIALOG_LOADING);
            removeDialog(DIALOG_LOADING);
        }
	}
	
	private static final String DATA_SEARCH_CURRENT_PAGE = "mSearchResultCurrentPage";
	private static final String DATA_SCENE_AREA_SEARCH_RESULT_COUNT = "mSceneAreaSearchResultCount";
	private static final String DATA_SCENE_AREA_SEARCH_RESULT_ID = "mSceneAreaSearchResultId";
	private static final String DATA_SCENE_AREA_SEARCH_RESULT_TITLE = "mSceneAreaSearchResultTitle";


	private void restoreSearchResultList(Bundle inState) {
		mSearchResultCurrentPage = inState.getInt(DATA_SEARCH_CURRENT_PAGE);
		mSceneAreaSearchResultCount = inState.getInt(DATA_SCENE_AREA_SEARCH_RESULT_COUNT);
		mSceneAreaSearchResultList[0] = inState.getStringArray(DATA_SCENE_AREA_SEARCH_RESULT_ID);
		mSceneAreaSearchResultList[1] = inState.getStringArray(DATA_SCENE_AREA_SEARCH_RESULT_TITLE);

		ListView listView = (ListView) mSceneViews[RESULT_ID]
			.findViewById(R.id.search_result_list_id);
		
		String mainContent = getResources().getString(R.string.search_result_title);
		TextView tv = (TextView) findViewById(R.id.search_condition_id);
		setTurnPageButtonVisibility(tv, mainContent, mSceneAreaSearchResultCount, 
			mSearchResultCurrentPage * LIST_SEARCH_RESULT_COUNT, 
			mSearchResultPrePage, mSearchResultNextPage);

		if (mSceneAreaSearchResultList[1] != null)
		listView.setAdapter(new ArrayAdapter<String>(SearchActivity.this, 
			android.R.layout.simple_list_item_1, mSceneAreaSearchResultList[1]));
	}

	private void saveSearchResultList(Bundle outState) {
		outState.putInt(DATA_SEARCH_CURRENT_PAGE, mSearchResultCurrentPage);
		outState.putInt(DATA_SCENE_AREA_SEARCH_RESULT_COUNT, mSceneAreaSearchResultCount);
		outState.putStringArray(DATA_SCENE_AREA_SEARCH_RESULT_ID, mSceneAreaSearchResultList[0]);
		outState.putStringArray(DATA_SCENE_AREA_SEARCH_RESULT_TITLE, mSceneAreaSearchResultList[1]);
	}

	/*
	 * 计算页码， resultCount当前页面的起始记录数
	 * countPerPage每个页面显示的记录数
	 * 返回： 页码
	 */
    private static int calResultPageCount(int resultCount, int countPerPage){
        int temp = resultCount / countPerPage;
        int temp2 = resultCount % countPerPage;
        int pageN = (temp2)!=0 ? (temp + 1): temp;        
        return pageN;
    }

    /*
     * 显示 内容(content) + (当前页码/总页数)
     */
	private void displayPageIndexInfo(TextView tv, String content, int totalRecordNum, int pageRecordNum, int countPerPage) {
		
		Resources res = getResources();
		String prefix = res.getString(R.string.prefix_page);
		String suffix = res.getString(R.string.suffix_page);
		int totalPage = calResultPageCount(totalRecordNum, countPerPage);
		int currentPage = calResultPageCount(pageRecordNum, countPerPage);
		if (totalPage == 0)
			currentPage = 0;
		String infoString = content;
		infoString += prefix + currentPage + "/" + totalPage + suffix;
		tv.setText(infoString);
	}
	
	/*
	 * number: 记录总数
	 * startIndex : 当前页的起始记录
	 * prePage : 向前页的按钮
	 * nextPage : 向后页的按钮
	 */
	private void setTurnPageButtonVisibility(TextView tv, String mainContent, int number, int startIndex, ImageButton prePage, ImageButton nextPage) {
		if (number < LIST_SEARCH_RESULT_COUNT) {
			prePage.setVisibility(View.GONE);
			nextPage.setVisibility(View.GONE);
		} else if (startIndex < LIST_SEARCH_RESULT_COUNT) {
			prePage.setVisibility(View.GONE);
			nextPage.setVisibility(View.VISIBLE);
		} else if ( number - startIndex <= LIST_SEARCH_RESULT_COUNT) {
			prePage.setVisibility(View.VISIBLE);
			nextPage.setVisibility(View.GONE);
		} else {
			prePage.setVisibility(View.VISIBLE);
			nextPage.setVisibility(View.VISIBLE);
		}
		displayPageIndexInfo(tv, mainContent, number, startIndex + LIST_SEARCH_RESULT_COUNT, LIST_SEARCH_RESULT_COUNT);
	}
	
    @Override
    protected Dialog onCreateDialog(int id) {
    	AlertDialog.Builder builder;
        switch (id) {
        case DIALOG_MONTH_SCENE_LIST:
        	builder = new AlertDialog.Builder(SearchActivity.this);
        	setListDialog(builder,
        			SearchActivity.this.getResources()
					.getString(R.string.select_scene_month_dialog_title),
					mMonthRecommendContent[1], DIALOG_MONTH_SCENE_LIST);
        	return builder.create();
        case DIALOG_RECOMMEND_SCENE_LIST:
        	builder = new AlertDialog.Builder(SearchActivity.this);
        	setListDialog(builder,
        			SearchActivity.this.getResources()
					.getString(R.string.select_scene_spot_dialog_title),
					mScenePageRecommendContent[1], DIALOG_RECOMMEND_SCENE_LIST);
        	return builder.create();
        case DIALOG_AROUND_SCENE_LIST:
        	builder = new AlertDialog.Builder(SearchActivity.this);
        	setListDialog(builder,
        			SearchActivity.this.getResources()
					.getString(R.string.select_scene_dialog_title),
					mScenePageAroundContent[1], DIALOG_AROUND_SCENE_LIST);
        	return builder.create();
        case DIALOG_LOADING:
        	return createLoadingDialog();
        }
        
        return null;
    }
    
    /*
     * 创建等待页面
     */
    private ProgressDialog createLoadingDialog() {
    	ProgressDialog dialog = new ProgressDialog(this);
    	dialog.setMessage(getResources().getString(R.string.info_loading));
    	dialog.setIndeterminate(true);
    	dialog.setCancelable(true);    	
    	return dialog;
    }
    
    /*
     * @see android.app.Activity.OnTitleIconClickListener#onTitleIconClick()
     * 如果是首页，点击后退出程序
     * 否则设置首页按钮，并显示首页
     */
	public void onTitleIconClick() {
		//BottomTabHost tabHost = getTabHost();
		TabHost tabHost = getTabHost();
		//current page is home page
		if (tabHost.getCurrentTabTag().equals(tab1) && 
				mCurrentSceneOperationViewIndex == SEARCH_ID) {
			finish();
			return;
		}
		
		hideAllViews();
		tabHost.setCurrentTabByTag(tab1);
		setCurrentSceneOperationView(SEARCH_ID);		
		//customTitleIcon(R.drawable.exit_pressed, R.drawable.exit_released, 
		//	R.string.exit_title, this);
	}
    
	/*
	 * 回退到首页，显示退出按钮
	 * 否则显示首页按钮
	 */
	private void changeTitleIconAsHomePage() {
		//BottomTabHost tabHost = getTabHost();
		TabHost tabHost = getTabHost();
		if (tabHost.getCurrentTabTag().equals(tab1) && 
				mCurrentSceneOperationViewIndex == SEARCH_ID) {
			//customTitleIcon(R.drawable.exit_pressed, R.drawable.exit_released, 
			//		R.string.exit_title, this);
			return;
		}
		//customTitleIcon(R.drawable.home_pressed, R.drawable.home_released, 
		//		R.string.home_title, this);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			
			//BottomTabHost tabHost = getTabHost();
			TabHost tabHost = getTabHost();
			String tag = tabHost.getCurrentTabTag();

			if (tag.equals(tab2)) {
            	if (goHotLineBackToUpLayer())
					return true;
			} else if (tag.equals(tab1)) {
				if (goBackToUpLayer())
					return true;
			} else if (tag.equals(tab3)) {
            	if (goCollectionBackToUpLayer())
					return true;
			}
			return super.onKeyDown(keyCode, event);
		}
		return super.onKeyDown(keyCode, event);
	}

	/*
	 * 景区页面的后退
	 * mShortcut = true标志景区页面是从本月热门推荐过来的，所以后退时直接回到首页
	 * 要注意景区页面、游记攻略页面自身内部也有2层时的退出， 即第一层时返回搜索列表
	 * 页面(mShortcut = false) 或 首页 (mShortcut = true) ; 若第二层时返回到
	 * 第一层
	 */
	private boolean goBackToUpLayer() {
		if (mCurrentSceneOperationViewIndex == SEARCH_ID) {
			return false;
		} else if (mCurrentSceneOperationViewIndex == RESULT_ID) {			
			setCurrentSceneOperationView(SEARCH_ID);
			changeTitleIconAsHomePage();
			return true;
		} else if (mCurrentSceneOperationViewIndex == SCENE_MAIN_ID) {
			if (mCurrentSceneContentViewIndex == SCENE_ID ||
					mCurrentSceneContentViewIndex == SCENE_SPOT_ID) {
				if (mCurrentSceneContentViewTab0Index == SCENE_SPOT_ID) {
            		mCurrentSceneContentViewTab0Index = SCENE_ID;
            		setCurrentSceneContentView(SCENE_ID);
					//showSceneContentView(SCENE_ID);
					return true;
				} else if (mCurrentSceneContentViewTab0Index == SCENE_ID) {
					if (mShortcut) {						
						setCurrentSceneOperationView(SEARCH_ID);
						changeTitleIconAsHomePage();
						mShortcut = false;
						return true;
					} else {
						setCurrentSceneOperationView(RESULT_ID);
						return true;
					}
				}
			} else if (mCurrentSceneContentViewIndex == ROUTE_ID) {
				if (mShortcut) {						
					setCurrentSceneOperationView(SEARCH_ID);
					changeTitleIconAsHomePage();
					mShortcut = false;
					return true;
				} else {
					setCurrentSceneOperationView(RESULT_ID);
					return true;
				}
			} else if (mCurrentSceneContentViewIndex == NOTE_ID ||
					mCurrentSceneContentViewIndex == NOTE_CONTENT_ID) {
				if (mCurrentSceneContentViewTab2Index == NOTE_CONTENT_ID) {
					mCurrentSceneContentViewTab2Index = NOTE_ID;
					setCurrentSceneContentView(NOTE_ID);
					//showSceneContentView(NOTE_ID);
					return true;
				} else if (mCurrentSceneContentViewTab2Index == NOTE_ID) {
					if (mShortcut) {						
						setCurrentSceneOperationView(SEARCH_ID);
						changeTitleIconAsHomePage();
						mShortcut = false;
						return true;
					} else {
						setCurrentSceneOperationView(RESULT_ID);
						return true;
					}
				}
			}
		}
		return false;
	}

	private void setCurrentSceneOperationView(int viewId) {
		mCurrentSceneOperationViewIndex = viewId;
		showSceneView(mCurrentSceneOperationViewIndex);
	}

	private void setCurrentSceneContentView(int viewId) {
		mCurrentSceneContentViewIndex = viewId;
		showSceneContentView(mCurrentSceneContentViewIndex);
	}

	private String[][] getCityNameAndId(String cityProvinceId) {
		return mDatabase.getCityNameAndId(cityProvinceId);
	}
	
	private static final int SCENE_AREA_COLLECTION = 0;
	private static final int NOTE_COLLECTION = 1;
	private static final int INFO_COLLECTION = 2;
	private static final int SCENE_SPOT_COLLECTION = 3;
	private static final int COLLECTION_LIST = 4;
	
	/*
	 * 如果没有收藏过，提示收藏成功
	 * 否则提示已经收藏过
	 */
	public void insertCollectionToDB(String id, String title, int subType, int mainType) {
		boolean ret = mDatabase.insertCollectionToDB(id, title, subType, mainType);
		if (ret) {
			Toast.makeText(SearchActivity.this, getResources().getString(R.string.collection_saved_successed), Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(SearchActivity.this, getResources().getString(R.string.collection_already_exist), Toast.LENGTH_SHORT).show();
		}
	}
	
	private static final String PREFIX_SCENE_AREA_ID = "ScenicDetailForLenovo.ashx?id=";
	private static final String PREFIX_SCENE_AREA_FLAG = "&flag=0";

	private String createSearchSceneAreaRequestUrl(int position) {
		return BASE_URL + PREFIX_SCENE_AREA_ID + mSceneAreaSearchResultList[0][position] + PREFIX_SCENE_AREA_FLAG;
	}

	private String createAroundSceneAreaRequestUrl(int position) {
		return BASE_URL + PREFIX_SCENE_AREA_ID + mScenePageAroundContent[0][position] + PREFIX_SCENE_AREA_FLAG;
	}

	private String createMonthSceneAreaRequestUrl(int position) {
		return BASE_URL + PREFIX_SCENE_AREA_ID + mMonthRecommendContent[0][position] + PREFIX_SCENE_AREA_FLAG;
	}
	
	/*
	 * 景区页面里的 景区(本月热门推荐、搜索结果里选择、景区页面里的周边景区)、
	 * 线路住宿、 游记攻略列表 的数据获取
	 */	
	private Handler mSceneAreaHandler;
	private static final int MSG_SCENE_AREA = 0;
	private static final int MSG_SCENE_RECOMMEND = 1;
	private static final int MSG_SCENE_AROUND = 2;
	private static final int MSG_ROUTE_ACCOMMODATION = 3;
	private static final int MSG_NOTE_LIST = 4;
	
	private static final String KEY_MSG_SCENE_AREA = "key_msg_scene_area";
	private static final String KEY_MSG_SCENE_RECOMMEND = "key_msg_scene_recommend";
	private static final String KEY_MSG_SCENE_AROUND = "key_msg_scene_around";
	private static final String KEY_MSG_ROUTE_ACCOMMODATION = "key_msg_route_accommodation";
	private static final String KEY_MSG_NOTE_LIST = "key_msg_note_list";
	
	private void loadSceneArea(int position, int listType) {
        //final String dest = getResources().getString(R.string.url1);
        //final HashMap<String, String> map = HttpUtil.parseSceneArea(HttpUtil.getJSONObject(dest));
		//String url = "http://nokia.hz.lotour.com/ScenicDetailForLenovo.ashx?id=1031&flag=0";
		String urlScene = null;
		mSceneAreaId = "0";
		switch (listType) {
			case SCENE_AREA_LIST_SOURCE_SEARCH:
				mSceneAreaId = mSceneAreaSearchResultList[0][position];
				urlScene = createSearchSceneAreaRequestUrl(position);
				break;
			case SCENE_AREA_LIST_SOURCE_AROUND:
				mSceneAreaId = mScenePageAroundContent[0][position];
				urlScene = createAroundSceneAreaRequestUrl(position);
				break;
			case SCENE_AREA_LIST_SOURCE_MONTH:
				mSceneAreaId = mMonthRecommendContent[0][position];
				urlScene = createMonthSceneAreaRequestUrl(position);
				break;
		}
		
		String urlScenePageRecommend = createScenePageRecommendRequestUrl(listType, position);
		String urlScenePageAround = createScenePageAroundRequestUrl(listType, position);
		String urlRouteAccommodation = createRouteAccommodationUrl(listType, position, LIST_TOTAL_REQUEST_COUNT);
		String urlNoteList = createNoteListRequestUrl(listType, position, LIST_TOTAL_REQUEST_COUNT);

		final String sceneAreaIdTmp = mSceneAreaId;
		mSceneAreaHandler = new Handler() {
			public void handleMessage(Message msg) {
				String objStr = null;
				JSONObject obj = null;
				
				switch(msg.what) {
				case MSG_SCENE_AREA:
					objStr = msg.getData().getString(KEY_MSG_SCENE_AREA);
					obj = HttpUtil.getJSONObject(objStr);					
					mSceneAreaDetail = HttpUtil.parseSceneArea(obj, SearchActivity.this);
					if (mSceneAreaDetail == null)
						return;					
					displaySceneAreaDetail(sceneAreaIdTmp);					
					break;					
				case MSG_SCENE_RECOMMEND:
					objStr = msg.getData().getString(KEY_MSG_SCENE_RECOMMEND);
					obj = HttpUtil.getJSONObject(objStr);
					//mScenePageRecommendContent = HttpUtil.parseRecommendScene(HttpUtil.getRequestStream(url));
					mScenePageRecommendContent = HttpUtil.parseRecommendScene(obj);
					loadScenePageRecommendFlipperContent();
					break;					
				case MSG_SCENE_AROUND:
					objStr = msg.getData().getString(KEY_MSG_SCENE_AROUND);
					obj = HttpUtil.getJSONObject(objStr);
					//mScenePageAroundContent = HttpUtil.parseAroundScene(HttpUtil.getRequestStream(url));
					mScenePageAroundContent = HttpUtil.parseAroundScene(obj);					
					loadScenePageAroundFlipperContent();
					break;
				case MSG_ROUTE_ACCOMMODATION:
					objStr = msg.getData().getString(KEY_MSG_ROUTE_ACCOMMODATION);
					obj = HttpUtil.getJSONObject(objStr);					
					mRouteAccommodationContent = HttpUtil.parseRoute(obj);
					mRouteCurrentPage = 0; // set start page index
					loadRouteAccommodation();
					break;
				case MSG_NOTE_LIST:
		        	objStr = msg.getData().getString(KEY_MSG_NOTE_LIST);
					obj = HttpUtil.getJSONObject(objStr);	
					String notListBuffer[] = HttpUtil.parseNoteList(obj);
					
					if (notListBuffer == null) 
						break;
		        
					int count = notListBuffer.length / 3;		        
					mNoteListTypes = new String[count];
					mNoteListTitles = new String[count];
					mNoteListIDs = new String[count];
		        
					for (int i = 0; i < count; i++) {
						mNoteListIDs[i] = notListBuffer[i * 3];
						mNoteListTitles[i] = notListBuffer[i * 3 + 1];
						mNoteListTypes[i] = notListBuffer[i * 3 + 2];
					}
					mNoteListCurrentPage = 0;
					loadNoteList();
				}
			}
		};
		
	    int msgTypes[] = { MSG_SCENE_AREA, 
	    				MSG_SCENE_RECOMMEND, 
	    				MSG_SCENE_AROUND, 
	    				MSG_ROUTE_ACCOMMODATION,
	    				MSG_NOTE_LIST };
	    
	    String msgKeys[] = { KEY_MSG_SCENE_AREA, 
	    				KEY_MSG_SCENE_RECOMMEND, 
	    				KEY_MSG_SCENE_AROUND,
	    				KEY_MSG_ROUTE_ACCOMMODATION,
	    				KEY_MSG_NOTE_LIST};
	    
		mLoadingTask = new DataLoadingTask(mSceneAreaHandler, msgTypes, msgKeys)
	    	.execute(urlScene, urlScenePageRecommend, urlScenePageAround, 
	    			urlRouteAccommodation, urlNoteList);
	}
	
	/*
	 * 景区页面的显示， 有折行显示的效果
	 */
	private void displaySceneAreaDetail(String sceneAreaId) {
		TextView title = (TextView) findViewById(R.id.scene_content_title_id);
		ImageView image = (ImageView) findViewById(R.id.scene_content_image_id);
		TextView content = (TextView) findViewById(R.id.scene_content_content_id);

		String buffer[] = mSceneAreaDetail;
		if (mSceneAreaDetail == null)
			return;
		
		if (!buffer[0].equals(NULL)) {
			title.setText(buffer[0]);
		}

		if (!buffer[1].equals(NULL)) {
			content.setText(buffer[1]);
			content.setVisibility(View.VISIBLE);
		} else {
			content.setVisibility(View.GONE);
		}
		
		View ticketRowView = (View) findViewById(R.id.scene_content_ticket_row);
		if (!buffer[5].equals(NULL)) {
			TextView v = (TextView) findViewById(R.id.scene_content_ticket);
			v.setText(buffer[5]);
			ticketRowView.setVisibility(View.VISIBLE);
		} else {
			ticketRowView.setVisibility(View.GONE);
		}
		View opentimeRowView = (View) findViewById(R.id.scene_content_opentime_row);
		if (!buffer[4].equals(NULL)) {
			TextView v = (TextView) findViewById(R.id.scene_content_opentime);
			v.setText(buffer[4]);						
			opentimeRowView.setVisibility(View.VISIBLE);
		} else {
			opentimeRowView.setVisibility(View.GONE);
		}
		View phoneRowView = (View) findViewById(R.id.scene_content_phone_row);
		if (!buffer[7].equals(NULL)) {
			TextView v = (TextView) findViewById(R.id.scene_content_phone);
			v.setText(buffer[7]);						
			phoneRowView.setVisibility(View.VISIBLE);
		} else {
			phoneRowView.setVisibility(View.GONE);
		}
		View addressRowView = (View) findViewById(R.id.scene_content_address_row);
		if (!buffer[6].equals(NULL)) {
			TextView v = (TextView) findViewById(R.id.scene_content_address);
			v.setText(buffer[6]);						
			addressRowView.setVisibility(View.VISIBLE);
		} else {
			addressRowView.setVisibility(View.GONE);
		}
		View ratingRowView = (View) findViewById(R.id.scene_content_rating_row);
		if (!buffer[2].equals(NULL)) {
			TextView v = (TextView) findViewById(R.id.scene_content_rating);
			v.setText(buffer[2]);						
			ratingRowView.setVisibility(View.VISIBLE);
		} else {
			ratingRowView.setVisibility(View.GONE);
		}
		View typeRowView = (View) findViewById(R.id.scene_content_type_row);
		if (!buffer[3].equals(NULL)) {
			TextView v = (TextView) findViewById(R.id.scene_content_type);
			v.setText(buffer[3]);						
			typeRowView.setVisibility(View.VISIBLE);
		} else {
			typeRowView.setVisibility(View.GONE);
		}
		
		if (!buffer[8].equals(NULL)) {
			loadImageFile(buffer[8], image);
			image.setVisibility(View.VISIBLE);
		} else {
			image.setVisibility(View.GONE);
		}

		final String sceneAreaIdTmp = sceneAreaId;
		final String titleTmp = buffer[0];
		Button button = (Button) findViewById(R.id.scene_content_collect_button_id);
		button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				insertCollectionToDB(sceneAreaIdTmp, titleTmp, 0, SCENE_AREA_COLLECTION);
			}
		});
	}

	/*
	 * 根据listType决定景区的ID值： listType对应本月热门推荐、搜索结果里选择、景区页面里的周边景区
	 */
	private String getSceneIdByListType(int listType, int position) {
		switch (listType) {
		case SCENE_AREA_LIST_SOURCE_SEARCH:
			return mSceneAreaSearchResultList[0][position];
		case SCENE_AREA_LIST_SOURCE_AROUND:
			return mScenePageAroundContent[0][position];
		case SCENE_AREA_LIST_SOURCE_MONTH:
			return mMonthRecommendContent[0][position];
		}
		return "0";
	}
	
	private static final String PREFIX_SCENE_PAGE_RECOMMEND = "RecommendedScenicListForLenovo.ashx?id=";
	private String createScenePageRecommendRequestUrl(int listType, int position) {		
		return BASE_URL + PREFIX_SCENE_PAGE_RECOMMEND + getSceneIdByListType(listType, position) + PREFIX_REQUEST_COUNT + LIST_SEARCH_RESULT_COUNT;
	}
	
	/*
	 * 景区页面里的推荐景点的显示
	 */
	private void loadScenePageRecommendFlipperContent() {
		//String dest = getResources().getString(R.string.url_scene);		
		//mScenePageRecommendContent = HttpUtil.parseRecommendScene(HttpUtil.getJSONObject(dest));
		//String url ="http://nokia.hz.lotour.com/RecommendedScenicListForLenovo.ashx?id=2059&n=10";
		
		//String url = createScenePageRecommendRequestUrl(position);
		//mScenePageRecommendContent = HttpUtil.parseRecommendScene(HttpUtil.getRequestStream(url));
		
		ViewFlipper flipper = ((ViewFlipper) findViewById(R.id.recommend_scene_flipper));
		flipper.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				//showDialog(DIALOG_RECOMMEND_SCENE_LIST);
				AlertDialog.Builder builder;
				builder = new AlertDialog.Builder(SearchActivity.this);
	        	setListDialog(builder,
	        			SearchActivity.this.getResources()
						.getString(R.string.select_scene_spot_dialog_title),
						mScenePageRecommendContent[1], DIALOG_RECOMMEND_SCENE_LIST);//TODO数据的错误
	        	builder.show();
			}
		});		
		
		flipper.removeAllViews();
		if (mScenePageRecommendContent[1] == null)
			return;
		int count = mScenePageRecommendContent[1].length;
		for (int i = 0; i < count; i++) {
			TextView view = getGenericView(mScenePageRecommendContent[1][i]);
			flipper.addView(view);
		}
		
		flipper.setInAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.slide_in_left));
		flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.slide_out_right));
		flipper.startFlipping();
	}
	
	/*
	 * 景区页面里的周边景区的显示
	 */
	private static final String PREFIX_SCENE_PAGE_AROUND = "SurroundingScenicList.ashx?id=";
	private String createScenePageAroundRequestUrl(int listType, int position) {
		return BASE_URL + PREFIX_SCENE_PAGE_AROUND + getSceneIdByListType(listType, position) + PREFIX_REQUEST_COUNT + LIST_SEARCH_RESULT_COUNT;
	}
	private void loadScenePageAroundFlipperContent() {
		//String dest = getResources().getString(R.string.url_spot);		
		//mScenePageAroundContent = HttpUtil.parseAroundScene(HttpUtil.getJSONObject(dest));
		//String url ="http://nokia.hz.lotour.com/SurroundingScenicList.ashx?id=2059&n=10";
		//String url = createScenePageAroundRequestUrl(position);
		//mScenePageAroundContent = HttpUtil.parseAroundScene(HttpUtil.getRequestStream(url));
		ViewFlipper flipper = ((ViewFlipper) findViewById(R.id.around_scene_flipper));
		flipper.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				//showDialog(DIALOG_AROUND_SCENE_LIST);
				AlertDialog.Builder builder = new AlertDialog.Builder(SearchActivity.this);
	        	setListDialog(builder,
	        			SearchActivity.this.getResources()
						.getString(R.string.select_scene_dialog_title),
						mScenePageAroundContent[1], DIALOG_AROUND_SCENE_LIST);
	        	builder.show();
			}
		});
		
		flipper.removeAllViews();
		if (mScenePageAroundContent[1] == null)
			return;
		int count = mScenePageAroundContent[1].length;
		for (int i = 0; i < count; i++) {
			TextView view = getGenericView(mScenePageAroundContent[1][i]);
			flipper.addView(view);
		}
		
		flipper.setInAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.slide_in_left));
		flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.slide_out_right));
		flipper.startFlipping();
	}

	/*
	 * 本月热门推荐的显示
	 */
	private static final String MONTH_RECOMMEND = "http://nokia.hz.lotour.com/topscenic.ashx";

	private void loadMonthRecommendFlipperContent() {
		//String dest = getResources().getString(R.string.url_scene);
		//mMonthRecommendContent = HttpUtil.parseMonthRecommend(HttpUtil.getJSONObject(dest));
		
		/*
		 * 如果网络通， 从网络上取数据， 如果取到，刷新数据库中的数据
		 * 否则， 显示数据库中的数据
		 * 主要是为了快速启动程序
		 */
		if (HttpUtil.getNetworkStatus(MONTH_RECOMMEND)) {
			mMonthRecommendContent = HttpUtil.parseMonthRecommend(HttpUtil.getRequestStreamArray(MONTH_RECOMMEND));
			if (mMonthRecommendContent[0] != null && mMonthRecommendContent[1] != null) {
				mDatabase.insertMonthRecommend(mMonthRecommendContent);
			}
		} else {
			mMonthRecommendContent = mDatabase.getMonthRecommendFromDB();
		}
		
		displayMonthRecommendFlipperContent();
	}
	
	private void displayMonthRecommendFlipperContent() {
		ViewFlipper flipper = ((ViewFlipper) findViewById(R.id.month_scene_flipper));
		flipper.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(DIALOG_MONTH_SCENE_LIST);
			}
		});
		
		flipper.removeAllViews();
		if (mMonthRecommendContent !=null && mMonthRecommendContent[1] != null) {
			int count = mMonthRecommendContent[1].length;
			for (int i = 0; i < count; i++) {
				TextView view = getGenericView(mMonthRecommendContent[1][i]);
				flipper.addView(view);
			}
		}
		
		flipper.setInAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.slide_in_left));
		flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.slide_out_right));
		flipper.startFlipping();
	}
	
	private static final String DATA_SCENE_AREA_DETAIL = "mSceneAreaDetail";
	private static final String DATA_SCENE_AREA_ID = "mSceneAreaId";
	
	private static final String DATA_SCENE_PAGE_RECOMMEND_ID = "mScenePageRecommendContentID";
	private static final String DATA_SCENE_PAGE_RECOMMEND_TITLE = "mScenePageRecommendContentTitle";
	private static final String DATA_SCENE_PAGE_AROUND_ID = "mScenePageAroundContentID";
	private static final String DATA_SCENE_PAGE_AROUND_TITLE = "mScenePageAroundContentTitle";
		
	private void saveSceneArea(Bundle outState) {
		outState.putString(DATA_SCENE_AREA_ID, mSceneAreaId);
		outState.putStringArray(DATA_SCENE_AREA_DETAIL, mSceneAreaDetail);		
		
		outState.putStringArray(DATA_SCENE_PAGE_RECOMMEND_ID, mScenePageRecommendContent[0]);
		outState.putStringArray(DATA_SCENE_PAGE_RECOMMEND_TITLE, mScenePageRecommendContent[1]);
		outState.putStringArray(DATA_SCENE_PAGE_AROUND_ID, mScenePageAroundContent[0]);
		outState.putStringArray(DATA_SCENE_PAGE_AROUND_TITLE, mScenePageAroundContent[1]);
	}

	private void restoreSceneArea(Bundle inState) {		
		mScenePageRecommendContent[0] = inState.getStringArray(DATA_SCENE_PAGE_RECOMMEND_ID);
		mScenePageRecommendContent[1] = inState.getStringArray(DATA_SCENE_PAGE_RECOMMEND_TITLE);
		mScenePageAroundContent[0] = inState.getStringArray(DATA_SCENE_PAGE_AROUND_ID);
		mScenePageAroundContent[1] = inState.getStringArray(DATA_SCENE_PAGE_AROUND_TITLE);                  

		// scene page
		mSceneAreaId = inState.getString(DATA_SCENE_AREA_ID);
		mSceneAreaDetail = inState.getStringArray(DATA_SCENE_AREA_DETAIL);
		if (mSceneAreaDetail == null)
			return;
		
		displaySceneAreaDetail(mSceneAreaId);
				
		loadScenePageRecommendFlipperContent();
		loadScenePageAroundFlipperContent();
		
		// route page
		String title = mSceneAreaDetail[0];
		TextView titleView = (TextView) findViewById(R.id.route_list_title_id);
		if (title != null)
			titleView.setText(title);
		// note page
    	titleView = (TextView) findViewById(R.id.note_list_title_id);
		if (title != null)
			titleView.setText(title);
	}

	/*
	 * 从网络上获取景点数据， 并显示
	 */
	private String mSceneSpotID;
	private String mSceneSpotTitle;
	private String mSceneSpotImage;
	private String mSceneSpotContent;
	
	private static final String PREFIX_SCENE_SPOT_ID = "ScenicDetailForLenovo.ashx?id=";
	private static final String PREFIX_SCENE_SPOT_FLAG = "&flag=1";

	private String createSceneSpotRequestUrl(int position) {
		return BASE_URL + PREFIX_SCENE_SPOT_ID + mScenePageRecommendContent[0][position] + PREFIX_SCENE_SPOT_FLAG;
	}

	private Handler mSceneSpotHandler;
	private static final int MSG_SCENE_SPOT = 0;
	private static final String KEY_MSG_SCENE_SPOT = "key_msg_scene_spot";
	
	private void loadSceneSpot(int position) {
        //final String dest = getResources().getString(R.string.url4);
        //final HashMap<String, String> map = HttpUtil.parseScentSpot(HttpUtil.getJSONObject(dest), this);
		String urlSceneSpot = createSceneSpotRequestUrl(position);
		final int tmpPos = position;
		mSceneSpotHandler = new Handler() {
			public void handleMessage(Message msg) {
				switch(msg.what) {
				case MSG_SCENE_SPOT:
					String objStr = msg.getData().getString(KEY_MSG_SCENE_SPOT);
					JSONObject obj = HttpUtil.getJSONObject(objStr);					
					final HashMap<String, String> map = HttpUtil.parseScentSpot(obj, SearchActivity.this);
					
					if (map == null)
						break;

					//final String sceneSpotId = mScenePageRecommendContent[0][tmpPos];
					mSceneSpotID = mScenePageRecommendContent[0][tmpPos];
					mSceneSpotTitle = map.get(HttpUtil.TITLE);
					mSceneSpotImage = map.get(HttpUtil.IMAGE);
					mSceneSpotContent = map.get(HttpUtil.CONTENT);						
					displaySceneSpot();
					break;
				}
			}
		};
		
	    int msgTypes[] = { MSG_SCENE_SPOT };
	    String msgKeys[] = { KEY_MSG_SCENE_SPOT };
		mLoadingTask = new DataLoadingTask(mSceneSpotHandler, msgTypes, msgKeys).execute(urlSceneSpot);
	}
	
	private void displaySceneSpot() {
		TextView title = (TextView) findViewById(R.id.scene_spot_content_title_id);
		ImageView image = (ImageView) findViewById(R.id.scene_spot_content_image_id);
		TextView content = (TextView) findViewById(R.id.scene_spot_content_content_id);
		
		title.setText(mSceneSpotTitle);
		content.setText(mSceneSpotContent);
		if (!image.equals(NULL)) {
			loadImageFile(mSceneSpotImage, image);
			image.setVisibility(View.VISIBLE);
		} else {
			image.setVisibility(View.GONE);
		}		

		Button button = (Button) findViewById(R.id.scene_spot_content_title_button_id);
		button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				insertCollectionToDB(mSceneSpotID, mSceneSpotTitle, 0, SCENE_SPOT_COLLECTION);
			}
		});
	}
	
	private static final String DATA_SCENE_SPOT_ID = "mSceneSpotID";
	private static final String DATA_SCENE_SPOT_TITLE = "mSceneSpotTitle";
	private static final String DATA_SCENE_SPOT_IMAGE = "mSceneSpotImage";
	private static final String DATA_SCENE_SPOT_CONTENT = "mSceneSpotContent";
	
	private void saveSceneSpot(Bundle outState) {
		outState.putString(DATA_SCENE_SPOT_ID, mSceneSpotID);
		outState.putString(DATA_SCENE_SPOT_TITLE, mSceneSpotTitle);
		outState.putString(DATA_SCENE_SPOT_IMAGE, mSceneSpotImage);
		outState.putString(DATA_SCENE_SPOT_CONTENT, mSceneSpotContent);
	}
	
	private void restoreSceneSpot(Bundle inState) {
		mSceneSpotID = inState.getString(DATA_SCENE_SPOT_ID);
		mSceneSpotTitle = inState.getString(DATA_SCENE_SPOT_TITLE);
		mSceneSpotImage = inState.getString(DATA_SCENE_SPOT_IMAGE);
		mSceneSpotContent = inState.getString(DATA_SCENE_SPOT_CONTENT);
		
		displaySceneSpot();
	}
	/*
	 * ViewFlipper对应的选择对话框
	 */
	private void setListDialog(AlertDialog.Builder builder, String title, String[] items, int listType) {
		CharSequence charItems[] = new CharSequence[items.length];
		for (int i = 0; i < items.length; i++) {
			charItems[i] = items[i].subSequence(0, items[i].length());
		}
		builder.setTitle(title);
		final int type = listType;
		builder.setItems(charItems, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int position) {
            	/*
				 * 出现无法连接网络时， 应不应进入搜索结果页面
				 */
            	if (!HttpUtil.getNetworkStatus(MONTH_RECOMMEND)) {
            		Toast.makeText(SearchActivity.this, getResources().getString(R.string.error_network), Toast.LENGTH_SHORT).show();
            		return;
            	}
            	if (DIALOG_RECOMMEND_SCENE_LIST == type) {
            		mCurrentSceneContentViewTab0Index = SCENE_SPOT_ID;
            		setCurrentSceneContentView(SCENE_SPOT_ID); ////TODO: ROTATION CHECK
            		//showSceneContentView(SCENE_SPOT_ID)
                	loadSceneSpot(position);
            	} else if(DIALOG_AROUND_SCENE_LIST == type) {
            		mCurrentSceneContentViewTab0Index = SCENE_ID;
            		setCurrentSceneContentView(SCENE_ID);//TODO: ROTATION CHECK
            		showSceneContentView(SCENE_ID);
                	loadSceneArea(position, SCENE_AREA_LIST_SOURCE_AROUND);
            	} else if(DIALOG_MONTH_SCENE_LIST == type) {
            		mCurrentSceneContentViewTab0Index = SCENE_ID;
					mCurrentSceneContentViewIndex = SCENE_ID;
					mCurrentSceneOperationViewIndex = SCENE_MAIN_ID;					
					loadSceneArea(position, SCENE_AREA_LIST_SOURCE_MONTH);
					mShortcut = true;
					displayScenePage();
					changeTitleIconAsHomePage();//从本月热门目的地推荐其他页面， 改变Title
            	}
            }
        });
	}

	/*
	 *  动态生成TextView
	 */
    private TextView getGenericView(String text) {
        AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
                ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        TextView textView = new TextView(SearchActivity.this);
        textView.setLayoutParams(lp);
        textView.setGravity(Gravity.CENTER);
        textView.setText(text);
        textView.setTextColor(0xFFFFFFFF);
		textView.setTextSize(20f);
		textView.setVisibility(View.VISIBLE);
        return textView;
    }
	
    private void loadImageFile(String fileUrl, ImageView imView) {
		if (fileUrl == null || fileUrl.equals(NULL))
			return;
		URL myFileUrl = null;
		try {
		     myFileUrl = new URL(fileUrl);
		} catch (MalformedURLException e) {
		     e.printStackTrace();
		}
		
		//imView.setImageURI(Uri.parse(fileUrl));
		//Log.d("___________", "size :"+VMRuntime.getRuntime().getExternalBytesAllocated());
		try {
			Log.d("___________", "size :"+VMRuntime.getRuntime().getExternalBytesAllocated());
			HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();
			
            BitmapFactory.Options opts = new BitmapFactory.Options();            
            //opts.inJustDecodeBounds = true;
            //opts.inSampleSize = 4;
            Bitmap bmImg = BitmapFactory.decodeStream(is, null, opts);            
			//Bitmap bmImg = BitmapFactory.decodeStream(is);
			imView.setImageBitmap(bmImg);
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
	
	private static final String PREFIX_ROUTE_ACCOMMODATION_ID = "LineHotelListForLenovo.ashx?id=";

	private String createRouteAccommodationUrl(int listType, int position, int count) {
		return BASE_URL + PREFIX_ROUTE_ACCOMMODATION_ID 
			+ getSceneIdByListType(listType, position) + PREFIX_REQUEST_COUNT + count;
	}

	private void loadRouteAccommodation() {
		//String url = "http://nokia.hz.lotour.com/LineHotelListForLenovo.ashx?id=1043&n=10";
        //String dest = getResources().getString(R.string.url_route);
        //String buffer[] = HttpUtil.parseRoute(HttpUtil.getJSONObject(dest));

		//String url = createRouteAccommodationUrl(position, LIST_SEARCH_RESULT_COUNT);
		//mRouteAccommodationContent = HttpUtil.parseRoute(HttpUtil.getRequestStream(url));
		loadRouteAccommodationList();
	}	
	
	private ImageButton mRoutePrePage;
	private ImageButton mRouteNextPage;
	private int mRouteCurrentPage = 0;
	
	private void loadRouteAccommodationList() {
		mRoutePrePage.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				--mRouteCurrentPage;
				displayRouteAccommodationList(mRouteCurrentPage);
			}
		});
		mRouteNextPage.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				++mRouteCurrentPage;
				displayRouteAccommodationList(mRouteCurrentPage);
			}
		});
		displayRouteAccommodationList(mRouteCurrentPage);
	}

	private void setRouteAccommodationTurnPageVisibility() {
		String mainContent = mSceneAreaDetail[0];
		TextView tv = (TextView) findViewById(R.id.route_list_title_id);
		int total = 0;
		int count = mRouteAccommodationContent.length / 6;
		total = LIST_TOTAL_REQUEST_COUNT < count ? LIST_TOTAL_REQUEST_COUNT : count;
		setTurnPageButtonVisibility(tv, mainContent, total, mRouteCurrentPage * LIST_SEARCH_RESULT_COUNT, 
				mRoutePrePage, mRouteNextPage);
	}
	
	private void displayRouteAccommodationList(int page) {	
		if (mRouteAccommodationContent == null)
			return;
		setRouteAccommodationTurnPageVisibility();
		
		String buffer[] = mRouteAccommodationContent;
		
		int totalCount = buffer.length / 6;
		int startIndex = page * LIST_SEARCH_RESULT_COUNT;
		int endIndex = ((page + 1) * LIST_SEARCH_RESULT_COUNT) > totalCount ? 
				totalCount : ((page + 1) * LIST_SEARCH_RESULT_COUNT);
		int count = endIndex - startIndex;
		
        String groups[] = new String[count];
        String children[][] = new String[count][1];
        String ids[] = new String[count];
        
        int i, j;
        for (i = startIndex, j = 0; i < endIndex || j < count; i++, j++) {
        	ids[j] = buffer[i * 6];
        	groups[j] = buffer[i * 6 + 1];
		}
		
        ExpandableListView mListView = (ExpandableListView) findViewById(R.id.route_list_id);
        ExpandableListAdapter adapter = new MyExpandableListAdapter(this, groups, children);
        mListView.setAdapter(adapter);
	}
	
	private static final String DATA_ROUTE_ACCOMMODATION_CONTENT = "mRouteAccommodationContent"; 
	private static final String DATA_ROUTE_ACCOMMODATION_CURRENT_PAGE = "mRouteCurrentPage";
	
	private void saveRouteAccommodation(Bundle outState) {
		outState.putInt(DATA_ROUTE_ACCOMMODATION_CURRENT_PAGE, mRouteCurrentPage);
		outState.putStringArray(DATA_ROUTE_ACCOMMODATION_CONTENT, 
			mRouteAccommodationContent);
	}

	private void restoreRouteAccommodation(Bundle inState) {
		mRouteCurrentPage = inState.getInt(DATA_ROUTE_ACCOMMODATION_CURRENT_PAGE);
		mRouteAccommodationContent = inState.getStringArray(DATA_ROUTE_ACCOMMODATION_CONTENT);
		loadRouteAccommodationList();
	}
	
	/*
	 * 线路住宿的页面
	 */
    private class MyExpandableListAdapter extends BaseExpandableListAdapter {
	    private final LayoutInflater mInflater;
        private String[] mGroups;
        private String[][] mChildren;

		public MyExpandableListAdapter(Context context, String[] groups, String[][]children) {
        	super();
    	    mInflater = LayoutInflater.from(context);
    	    mGroups = groups;
    	    mChildren = children;
	    }
        
        public Object getChild(int groupPosition, int childPosition) {
            return mChildren[groupPosition][childPosition];
        }

        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        public int getChildrenCount(int groupPosition) {
            return mChildren[groupPosition].length;
        }
        
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
                View convertView, ViewGroup parent) {
			if (convertView == null) {
            	convertView = mInflater.inflate(R.layout.expand_child, parent, false);
        	}
			
			String buffer[] = mRouteAccommodationContent;
			
			int i = groupPosition;
			View v = null;
			TextView tv = null;
			
			v = (View) convertView.findViewById(R.id.project_row);
			tv = (TextView) convertView.findViewById(R.id.project);
			setView(v, tv, buffer[i * 6 + 2]);
		
			v = (View) convertView.findViewById(R.id.price_row);
			tv = (TextView) convertView.findViewById(R.id.price);
			setView(v, tv, buffer[i * 6 + 3]);
		
			v = (View) convertView.findViewById(R.id.route_phone_row);
			tv = (TextView) convertView.findViewById(R.id.route_phone);
			setView(v, tv, buffer[i * 6 + 4]);
		
			v = (View) convertView.findViewById(R.id.type_row);
			tv = (TextView) convertView.findViewById(R.id.type);			
			String infoString = null;
			if (buffer[i * 6 + 5].equals("0"))
				infoString = getResources().getString(R.string.route_line);
			else
				infoString = getResources().getString(R.string.route_accommodation);			
			setView(v, tv, infoString);
            
            return convertView;
        }

        private void setView(View v, TextView tv, String str) {        	
			if (str.equals(NULL)) {
				v.setVisibility(View.GONE);
			} else {
				tv.setText(str);
				v.setVisibility(View.VISIBLE);
			}
        }
        
        public Object getGroup(int groupPosition) {
            return mGroups[groupPosition];
        }

        public int getGroupCount() {
            return mGroups.length;
        }

        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        public View getGroupView(int groupPosition, boolean isExpanded, View convertView,
                ViewGroup parent) {

			if (convertView == null) {
            	convertView = mInflater.inflate(R.layout.expand_group, parent, false);
        	}
            TextView textView = (TextView) convertView;
            textView.setText(getGroup(groupPosition).toString());
            return textView;
        }

        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

        public boolean hasStableIds() {
            return true;
        }
    }
	
	private static final String PREFIX_NOTE_LIST_ID = "TravelsListForLenovo.ashx?id=";

	private String createNoteListRequestUrl(int listType, int position, int count) {
		return BASE_URL + PREFIX_NOTE_LIST_ID + getSceneIdByListType(listType, position)
			+ PREFIX_REQUEST_COUNT + count;
	}

	private int mNoteListCurrentPage = 0;
	private ImageButton mNoteListPrePage;
	private ImageButton mNoteListNextPage;
	
    private void loadNoteList() {
    	mNoteListPrePage.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				--mNoteListCurrentPage;
				displayNoteList(mNoteListCurrentPage);
			}
		});
    	mNoteListNextPage.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				++mNoteListCurrentPage;
				displayNoteList(mNoteListCurrentPage);
			}
		});
    	
    	displayNoteList(mNoteListCurrentPage);
    }

	private void setNoteListTurnPageVisibility() {		
		String mainContent = mSceneAreaDetail[0];
		TextView tv = (TextView) findViewById(R.id.note_list_title_id);
		int total = 0;
		total = LIST_TOTAL_REQUEST_COUNT < mNoteListIDs.length ? LIST_TOTAL_REQUEST_COUNT : mNoteListIDs.length;
		setTurnPageButtonVisibility(tv, mainContent, total, mNoteListCurrentPage * LIST_SEARCH_RESULT_COUNT, 
				mNoteListPrePage, mNoteListNextPage);
	}
	
	private void displayNoteList(int page) {
    	ListView listView = (ListView) findViewById(R.id.note_list_id);
    	
		if (mNoteListTitles == null) {
			listView.setAdapter(null);
			return;
		}
		setNoteListTurnPageVisibility();
		
		int totalCount = mNoteListTitles.length;//TODO
		final int startIndex = mNoteListCurrentPage * LIST_SEARCH_RESULT_COUNT;
		int endIndex = ((page + 1) * LIST_SEARCH_RESULT_COUNT) > totalCount ? 
				totalCount : ((page + 1) * LIST_SEARCH_RESULT_COUNT);
		int count = endIndex - startIndex;
		
		String buffer[] = new String[count];
		for (int i = 0; i < count; i++ )
			buffer[i] = mNoteListTitles[i + startIndex];
		
		listView.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, buffer));
		
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				mCurrentSceneContentViewTab2Index = NOTE_CONTENT_ID;
				setCurrentSceneContentView(NOTE_CONTENT_ID);
				loadNoteContent(startIndex + position);
			}
		});
	}

	private static final String DATA_NOTE_LIST_IDS = "mNoteListIDs";
	private static final String DATA_NOTE_LIST_TITLES = "mNoteListTitles";
	private static final String DATA_NOTE_LIST_TYPES = "mNoteListTypes";
	private static final String DATA_NOTE_LIST_CURRENT_PAGE = "mNoteListCurrentPage";

    private void saveNoteList(Bundle outState) {
    	outState.putInt(DATA_NOTE_LIST_CURRENT_PAGE, mNoteListCurrentPage);
		outState.putStringArray(DATA_NOTE_LIST_IDS, mNoteListIDs);
		outState.putStringArray(DATA_NOTE_LIST_TITLES, mNoteListTitles);
		outState.putStringArray(DATA_NOTE_LIST_TYPES, mNoteListTypes);
	}

	private void restoreNoteList(Bundle inState) {
		mNoteListCurrentPage = inState.getInt(DATA_NOTE_LIST_CURRENT_PAGE);
		mNoteListIDs = inState.getStringArray(DATA_NOTE_LIST_IDS);
		mNoteListTitles = inState.getStringArray(DATA_NOTE_LIST_TITLES);
		mNoteListTypes = inState.getStringArray(DATA_NOTE_LIST_TYPES);

    	displayNoteList(mNoteListCurrentPage);
	}

	private static final String PREFIX_NOTE_CONTENT_ID = "TravelsDetailForlenvo.ashx?id=";
	private static final String PREFIX_NOTE_CONTENT_FLAG = "&flag=";

	private String createNoteContentRequestUrl(int position) {
		return BASE_URL + PREFIX_NOTE_CONTENT_ID + mNoteListIDs[position] 
			+ PREFIX_NOTE_CONTENT_FLAG + mNoteListTypes[position];
	}

	/*
	 * 游记攻略详细内容显示
	 */	
	private Handler mNoteContentHandler;
	private static final int MSG_NOTE_CONTENT = 0;
	private static final String KEY_MSG_NOTE_CONTENT = "key_msg_note_content";
	
	private void loadNoteContent(int position) {
        //final String dest = getResources().getString(R.string.url5);
        //final HashMap<String, String> map = HttpUtil.parseNoteContent(HttpUtil.getJSONObject(dest), this);
        //String url = "http://nokia.hz.lotour.com/TravelsDetailForlenvo.ashx?id=1043&flag=0";
		
		String urlNoteContent = createNoteContentRequestUrl(position);
		final int tmpPos = position;
		mNoteContentHandler = new Handler() {
			
			public void handleMessage(Message msg) {
				switch(msg.what) {
				case MSG_NOTE_CONTENT:
					String objStr = msg.getData().getString(KEY_MSG_NOTE_CONTENT);
					JSONObject obj = HttpUtil.getJSONObject(objStr);
					final HashMap<String, String> map = HttpUtil.parseNoteContent(obj, SearchActivity.this);

					if (map == null)
						break;
					
					mNoteContentTitle = map.get(HttpUtil.TITLE);
					mNoteContentContent = map.get(HttpUtil.CONTENT);
					mNoteContentAuthor = map.get(HttpUtil.USERNAME);
					mNoteContentID = map.get(HttpUtil.ID);
					mNoteContentType = mNoteListTypes[tmpPos];

					displayNoteListContent();
					break;
				}
			}
		};
		
	    int msgTypes[] = { MSG_NOTE_CONTENT };
	    String msgKeys[] = { KEY_MSG_NOTE_CONTENT };
		mLoadingTask = new DataLoadingTask(mNoteContentHandler, msgTypes, msgKeys).execute(urlNoteContent);
	}

	private void displayNoteListContent() {
		TextView title = (TextView) findViewById(R.id.note_content_title_id);
		TextView author = (TextView) findViewById(R.id.note_content_author_id);
		TextView content = (TextView) findViewById(R.id.note_content_content_id);
	
		title.setText(mNoteContentTitle);
		content.setText(mNoteContentContent);
		author.setText(mNoteContentAuthor);
		
		Button button = (Button) findViewById(R.id.note_content_title_button_id);
		button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				insertCollectionToDB(mNoteContentID, mNoteContentTitle, 
					Integer.parseInt(mNoteContentType), NOTE_COLLECTION);
			}
		});
	}

	private static final String DATA_NOTE_CONTENT_TITLE = "mNoteContentTitle";
	private static final String DATA_NOTE_CONTENT_CONTENT = "mNoteContentContent";
	private static final String DATA_NOTE_CONTENT_AUTHOR = "mNoteContentAuthor";
	private static final String DATA_NOTE_CONTENT_ID = "mNoteContentID";
	private static final String DATA_NOTE_CONTENT_TYPE = "mNoteContentType";

	private void saveNoteContent(Bundle outState) {
		outState.putString(DATA_NOTE_CONTENT_TITLE, mNoteContentTitle);
		outState.putString(DATA_NOTE_CONTENT_CONTENT, mNoteContentContent);
		outState.putString(DATA_NOTE_CONTENT_AUTHOR, mNoteContentAuthor);
		outState.putString(DATA_NOTE_CONTENT_ID, mNoteContentID);
		outState.putString(DATA_NOTE_CONTENT_TYPE, mNoteContentType);
	}

	private void restoreNoteContent(Bundle inState) {
		mNoteContentTitle = inState.getString(DATA_NOTE_CONTENT_TITLE);
		mNoteContentContent = inState.getString(DATA_NOTE_CONTENT_CONTENT);
		mNoteContentAuthor = inState.getString(DATA_NOTE_CONTENT_AUTHOR);
		mNoteContentID = inState.getString(DATA_NOTE_CONTENT_ID);
		mNoteContentType = inState.getString(DATA_NOTE_CONTENT_TYPE);
		
		displayNoteListContent();
	}

	private static final String DATA_CURRENT_SCENE_OPERATION_VIEW_INDEX = "mCurrentSceneOperationViewIndex";
	private static final String DATA_CURRENT_SCENE_CONTENT_VIEW_TAB0_INDEX =
		"mCurrentSceneContentViewTab0Index";
	private static final String DATA_CURRENT_SCENE_CONTENT_VIEW_TAB2_INDEX =
		"mCurrentSceneContentViewTab2Index";
	private static final String DATA_CURRENT_SCENE_CONTENT_VIEW_INDEX = "mCurrentSceneContentViewIndex";
	private static final String DATA_CURRENT_TAB_INDEX = "mCurrentTabIndex";

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		
		outState.putInt(DATA_CURRENT_SCENE_OPERATION_VIEW_INDEX, mCurrentSceneOperationViewIndex);
		outState.putInt(DATA_CURRENT_SCENE_CONTENT_VIEW_TAB0_INDEX, mCurrentSceneContentViewTab0Index);
		outState.putInt(DATA_CURRENT_SCENE_CONTENT_VIEW_TAB2_INDEX, mCurrentSceneContentViewTab2Index);
		outState.putInt(DATA_CURRENT_SCENE_CONTENT_VIEW_INDEX, mCurrentSceneContentViewIndex);

		//BottomTabHost tabHost = getTabHost();
		TabHost tabHost = getTabHost();
		outState.putInt(DATA_CURRENT_TAB_INDEX, tabHost.getCurrentTab());

		saveSearchConditionPage(outState);
		saveSearchResultList(outState);
		saveSceneArea(outState);
		saveSceneSpot(outState);
		saveRouteAccommodation(outState);
		saveNoteList(outState);
		saveNoteContent(outState);

		saveHotLinePage(outState);
		saveCollectionPage(outState);
	}

	private void initHotLinePage() {
		mHotLinePages[HOTLINE_LIST_PAGE] = (View) findViewById(R.id.hotline_list);
        mHotLinePages[HOTLINE_CONTENT_PAGE] = (View) findViewById(R.id.hotline_content);
	}
	
	// Hotline page related function
    private void loadHotLinePage() {
    	setCurrentHotLinePage(HOTLINE_LIST_PAGE);
		loadHotLineList(false);
    }

    private void showCurrentHotLinePage(int index) {
        for (int i = 0; i < mHotLinePages.length; i++) {
            mHotLinePages[i].setVisibility(View.GONE);
        }
        mHotLinePages[index].setVisibility(View.VISIBLE);
    }

    private void setCurrentHotLinePage(int viewId) {
        mHotLineCurrentPageIndex = viewId;
        showCurrentHotLinePage(mHotLineCurrentPageIndex);
    }

	private static final String PREFIX_HOTLINE_LIST = "NewsListForLenovo.ashx?n=";

	private String createPrefixHotLineListRequestUrl(int count) {
		return BASE_URL + PREFIX_HOTLINE_LIST + count;
	}

	private Handler mHotLineListHandler;
	private static final int MSG_HOTLINE_LIST = 0;
	private static final String KEY_MSG_HOTLINE_LIST = "key_msg_hotline_list";

	private void loadHotLineList(boolean ready) {
		if (!ready) {
			//String url = "http://nokia.hz.lotour.com/NewsListForLenovo.ashx?n=10";
			//String urlHotLineList = createPrefixHotLineListRequestUrl(LIST_SEARCH_RESULT_COUNT);
			String urlHotLineList = createPrefixHotLineListRequestUrl(LIST_TOTAL_REQUEST_COUNT);
			mHotLineListHandler = new Handler() {
				public void handleMessage(Message msg) {
					switch(msg.what) {
					case MSG_HOTLINE_LIST:
						String objStr = msg.getData().getString(KEY_MSG_HOTLINE_LIST);
						JSONObject obj = HttpUtil.getJSONObject(objStr);
						mHotLineListContent = HttpUtil.parseHotLineList(obj);
						displayHotLineList();
						break;
					}
				}
			};
			int msgTypes[] = { MSG_HOTLINE_LIST };
			String msgKeys[] = { KEY_MSG_HOTLINE_LIST };
			mLoadingTask = new DataLoadingTask(mHotLineListHandler, msgTypes, msgKeys).execute(urlHotLineList);
		} else {
			displayHotLineList();
		}
	}
	
	private void displayHotLineList() {
        ListView listView = (ListView) findViewById(R.id.hotline_list_id);
        if (mHotLineListContent != null && mHotLineListContent[1] != null) {
        	listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, 
        			mHotLineListContent[1]));
        }
        else
        	listView.setAdapter(null);

		listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {            	
                setCurrentHotLinePage(HOTLINE_CONTENT_PAGE);
				loadHotLineDetail(false, position);
            }
        });
	}

	private static final String PREFIX_HOTLINE_DETAIL = "NewsDetailForLenvo.ashx?id=";

	private String createPrefixHotLineDetailRequestUrl(int position) {
		return BASE_URL + PREFIX_HOTLINE_DETAIL + mHotLineListContent[0][position];
	}

	private Handler mHotLineDetailHandler;
	private static final int MSG_HOTLINE_DETAIL = 0;
	private static final String KEY_MSG_HOTLINE_DETAIL = "key_msg_hotline_detail";

	private void loadHotLineDetail(boolean ready, int position) {
		if (!ready) {
			//String url = "http://nokia.hz.lotour.com/NewsDetailForLenvo.ashx?id=359093";
			String urlHotlineDetail = createPrefixHotLineDetailRequestUrl(position);
			
			mHotLineDetailHandler = new Handler() {
				public void handleMessage(Message msg) {
					switch(msg.what) {
					case MSG_HOTLINE_DETAIL:
						String objStr = msg.getData().getString(KEY_MSG_HOTLINE_DETAIL);
						String buffer[] = splitTitleAndContent(objStr);
						
						if (buffer == null)
							break;
						
				        HashMap<String, String> map = HttpUtil.parseHotLineContent(HttpUtil.getJSONObject(buffer[0]), SearchActivity.this);
						mHotLineContentContentID = map.get(HttpUtil.ID);
						mHotLineContentContentTitle = map.get(HttpUtil.TITLE);
						
						mHotLineContentContent = buffer[1];
						displayHotLineDetail();
						break;
					}
				}
			};
			
		    int msgTypes[] = { MSG_HOTLINE_DETAIL };
		    String msgKeys[] = { KEY_MSG_HOTLINE_DETAIL };
			mLoadingTask = new DataLoadingTask(mHotLineDetailHandler, msgTypes, msgKeys).execute(urlHotlineDetail);
		
			/*String dest = HttpUtil.getResponseString(url)
			String buffer[] = splitTitleAndContent(dest);

	        final HashMap<String, String> map = HttpUtil.parseHotLineContent(HttpUtil.getJSONObject(buffer[0]), this);
			mHotLineContentContentID = map.get(HttpUtil.ID);
			mHotLineContentContentTitle = map.get(HttpUtil.TITLE);
			mHotLineContentContent = buffer[1];
			displayHotLineDetail();*/
		} else {
			displayHotLineDetail();
		}
	}
	
	private void displayHotLineDetail() {
		final String mimeType = "text/html";
        final String encoding = "utf-8";

		TextView title = (TextView) findViewById(R.id.hotline_content_title_id);
		WebView content = (WebView) findViewById(R.id.hotline_content_content_id);

		if (mHotLineContentContentTitle != null) {
			title.setText(mHotLineContentContentTitle);
			title.setVisibility(View.VISIBLE);
		} else {
			title.setVisibility(View.GONE);
		}
		
		if (mHotLineContentContent != null) {
			content.setVisibility(View.VISIBLE);
			content.loadData(mHotLineContentContent, mimeType, encoding);
		} else {
			content.setVisibility(View.GONE);
		}
		
	
		Button button = (Button) findViewById(R.id.hotline_content_title_button_id);
		button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
				insertCollectionToDB(mHotLineContentContentID, mHotLineContentContentTitle, 0, INFO_COLLECTION);
            }
        });
	}
	
	private String[] splitTitleAndContent(String dest) {
		String result[] = new String[2];
		final String curve = "}";
		String tmp = dest.replaceFirst(",content:", curve);
		int index = tmp.indexOf(curve);
		result[0] = tmp.substring(0, index + 1); //include curve, for json object
		int lastIndex = tmp.lastIndexOf(curve);
		result[1] = tmp.substring(index + 1, lastIndex);
		return result;
	}

    private boolean goHotLineBackToUpLayer() {
        if (mHotLineCurrentPageIndex == HOTLINE_LIST_PAGE) {
            return false;
        } else if (mHotLineCurrentPageIndex == HOTLINE_CONTENT_PAGE) {
            setCurrentHotLinePage(HOTLINE_LIST_PAGE);
            return true;
        }
        return false;
    }

    private boolean goCollectionBackToUpLayer() {
        if (mCollectionPageIndex == COLLECTION_LIST) {
            return false;
        } else if (mCollectionPageIndex == SCENE_AREA_COLLECTION ||
        		mCollectionPageIndex == NOTE_COLLECTION ||
        		mCollectionPageIndex == INFO_COLLECTION ||
        		mCollectionPageIndex == SCENE_SPOT_COLLECTION ) {
        	setCurrentCollectionContentView(COLLECTION_LIST);
            return true;
        }
        return false;
    }
    
	// for display correct tab when tab is switched
	private void hideAllViews() {
		for (int i = 0; i < mSceneViews.length; i++) {
			mSceneViews[i].setVisibility(View.INVISIBLE);
		}
		for (int i = 0; i < mSceneContentViews.length; i++) {
			mSceneContentViews[i].setVisibility(View.INVISIBLE);
		}
		for (int i = 0; i < mScenePageTabButton.length; i++) {
			mScenePageTabButton[i].setVisibility(View.INVISIBLE);
		}
        for (int i = 0; i < mHotLinePages.length; i++) {
            mHotLinePages[i].setVisibility(View.INVISIBLE);
        }
		
		//findViewById(R.id.collection_page_id).setVisibility(View.INVISIBLE)
		for (int i = 0; i < mCollectionViews.length; i++) {
			mCollectionViews[i].setVisibility(View.INVISIBLE);
		}
		
		findViewById(R.id.about_id).setVisibility(View.INVISIBLE);
	}

	private void showSelectedTabButton() {
		if (mCurrentSceneContentViewIndex == SCENE_ID || mCurrentSceneContentViewIndex == SCENE_SPOT_ID )
			showScenePageTabButtons(SCENE_BUTTON);
		else if (mCurrentSceneContentViewIndex == NOTE_ID || mCurrentSceneContentViewIndex == NOTE_CONTENT_ID )
			showScenePageTabButtons(NOTE_BUTTON);
		else if (mCurrentSceneContentViewIndex == ROUTE_ID )
			showScenePageTabButtons(ROUTE_BUTTON);
	}

	private void displayScenePage() {
		showSceneView(mCurrentSceneOperationViewIndex);
		if (mCurrentSceneOperationViewIndex == SCENE_MAIN_ID) {
			showSceneContentView(mCurrentSceneContentViewIndex);
			showSelectedTabButton();
		}
	}

	private void displayHotLinePage() {
        showCurrentHotLinePage(mHotLineCurrentPageIndex);
	}

	private void displayCollectionListPage() {
		loadCollectionListPage();
		showCollectionContentView(mCollectionPageIndex);
	}

	private void displayAboutPage() {
		findViewById(R.id.about_id).setVisibility(View.VISIBLE);
	}
    
	private void saveHotLinePage(Bundle outState) {
		outState.putString(DATA_HOTLINE_CONTENT_ID, mHotLineContentContentID);
		outState.putString(DATA_HOTLINE_CONTENT_TITLE, mHotLineContentContentTitle);
		outState.putString(DATA_HOTLINE_CONTENT_CONTENT, mHotLineContentContent);
		
		if (mHotLineListContent != null) {
			outState.putStringArray(DATA_HOTLINE_LIST_ID, mHotLineListContent[0]);
			outState.putStringArray(DATA_HOTLINE_LIST_TITLE, mHotLineListContent[1]);
		}

		outState.putInt(DATA_HOTLINE_CURRENT_PAGE_INDEX, mHotLineCurrentPageIndex);
	}

	private void restoreHotLinePage(Bundle inState) {
		int mHotLineCurrentPageIndex = inState.getInt(DATA_HOTLINE_CURRENT_PAGE_INDEX, HOTLINE_LIST_PAGE);

		mHotLineListContent[0] = inState.getStringArray(DATA_HOTLINE_LIST_ID);
		mHotLineListContent[1] = inState.getStringArray(DATA_HOTLINE_LIST_TITLE);

		mHotLineContentContentID = inState.getString(DATA_HOTLINE_CONTENT_ID);
		mHotLineContentContentTitle = inState.getString(DATA_HOTLINE_CONTENT_TITLE);
		mHotLineContentContent = inState.getString(DATA_HOTLINE_CONTENT_CONTENT);

		setCurrentHotLinePage(mHotLineCurrentPageIndex);

		displayHotLineList();
		loadHotLineDetail(true, 0); // 0 is meaningless
	}

	// collection list page
	private int mCollectionPageIndex = COLLECTION_LIST;
	
	private String[] mCollectionListIds;
	private String[] mCollectionListTitles;
	private String[] mCollectionListTypes;
	private String[] mCollectionListMainTypes;
	
	private String[] mCollectionSceneAreaDetail;
	
	private String mCollectionNoteContentTitle;
	private String mCollectionNoteContentContent;
	private String mCollectionNoteContentAuthor;
	
	private String mCollectionHotLineContentContentTitle;
	private String mCollectionHotLineContentContent;

	private String mCollectionSceneSpotTitle;
	private String mCollectionSceneSpotImage;
	private String mCollectionSceneSpotContent;
	
	private static final int COLLECTION_CONTENT_PAGE_COUNT = 5;
	private View mCollectionViews[] = new View[COLLECTION_CONTENT_PAGE_COUNT];
	
	private static final String DATA_COLLECTION_PAGE_INDEX = "mCollectionPageIndex";	
	private static final String DATA_COLLECTION_LIST_IDS = "mCollectionListIds";
	private static final String DATA_COLLECTION_LIST_TITLES = "mCollectionListTitles";
	private static final String DATA_COLLECTION_LIST_TYPES = "mCollectionListTypes";
	private static final String DATA_COLLECTION_LIST_MAIN_TYPES = "mCollectionListMainTypes";
	
	private static final String DATA_COLLECTION_SCENE_AREA_DETAIL = "mCollectionSceneAreaDetail";
	
	private static final String DATA_COLLECTION_NOTE_CONTENT_TITLE = "mCollectionNoteContentTitle";
	private static final String DATA_COLLECTION_NOTE_CONTENT_CONTENT = "mCollectionNoteContentContent";
	private static final String DATA_COLLECTION_NOTE_CONTENT_AUTHOR = "mCollectionNoteContentAuthor";	
	private static final String DATA_COLLECTION_HOTLINE_CONTENT_CONTENT_TITLE = "mCollectionHotLineContentContentTitle";
	private static final String DATA_COLLECTION_HOTLINE_CONTENT_CONTENT = "mCollectionHotLineContentContent";
	private static final String DATA_COLLECTION_SCENE_SPOT_TITLE = "mCollectionSceneSpotTitle";
	private static final String DATA_COLLECTION_SCENE_SPOT_IMAGE = "mCollectionSceneSpotImage";
	private static final String DATA_COLLECTION_SCENE_SPOT_CONTENT = "mCollectionSceneSpotContent";
		
	private void saveCollectionPage(Bundle outState) {
		outState.putInt(DATA_COLLECTION_PAGE_INDEX, mCollectionPageIndex);
		outState.putStringArray(DATA_COLLECTION_LIST_IDS, mCollectionListIds);
		outState.putStringArray(DATA_COLLECTION_LIST_TITLES, mCollectionListTitles);
		outState.putStringArray(DATA_COLLECTION_LIST_TYPES, mCollectionListTypes);
		outState.putStringArray(DATA_COLLECTION_LIST_MAIN_TYPES, mCollectionListMainTypes);
		
		outState.putStringArray(DATA_COLLECTION_SCENE_AREA_DETAIL, mCollectionSceneAreaDetail);

		outState.putString(DATA_COLLECTION_NOTE_CONTENT_TITLE, mCollectionNoteContentTitle);
		outState.putString(DATA_COLLECTION_NOTE_CONTENT_CONTENT, mCollectionNoteContentContent);
		outState.putString(DATA_COLLECTION_NOTE_CONTENT_AUTHOR, mCollectionNoteContentAuthor);
		outState.putString(DATA_COLLECTION_HOTLINE_CONTENT_CONTENT_TITLE, mCollectionHotLineContentContentTitle);
		outState.putString(DATA_COLLECTION_HOTLINE_CONTENT_CONTENT, mCollectionHotLineContentContent);		
		outState.putString(DATA_COLLECTION_SCENE_SPOT_TITLE, mCollectionSceneSpotTitle);
		outState.putString(DATA_COLLECTION_SCENE_SPOT_IMAGE, mCollectionSceneSpotImage);
		outState.putString(DATA_COLLECTION_SCENE_SPOT_CONTENT, mCollectionSceneSpotContent);
	}
	
	private void restoreCollectionPage(Bundle inState) {
		mCollectionPageIndex = inState.getInt(DATA_COLLECTION_PAGE_INDEX);
		
		mCollectionListIds = inState.getStringArray(DATA_COLLECTION_LIST_IDS);
		mCollectionListTitles = inState.getStringArray(DATA_COLLECTION_LIST_TITLES);
		mCollectionListTypes = inState.getStringArray(DATA_COLLECTION_LIST_TYPES);
		mCollectionListMainTypes = inState.getStringArray(DATA_COLLECTION_LIST_MAIN_TYPES);

        ListView collectionListView = (ListView) findViewById(R.id.collection_list_id);
		if (mCollectionListTitles != null && mCollectionListTitles.length > 0) {
        	collectionListView.setAdapter(new ArrayAdapter<String>(this, 
				android.R.layout.simple_list_item_1, mCollectionListTitles));
		}
		
		mCollectionSceneAreaDetail = inState.getStringArray(DATA_COLLECTION_SCENE_AREA_DETAIL);
		displayCollectionSceneAreaDetail();
		
		mCollectionNoteContentTitle = inState.getString(DATA_COLLECTION_NOTE_CONTENT_TITLE);
		mCollectionNoteContentContent = inState.getString(DATA_COLLECTION_NOTE_CONTENT_CONTENT);
		mCollectionNoteContentAuthor = inState.getString(DATA_COLLECTION_NOTE_CONTENT_AUTHOR);
		loadCollectionNoteContent(true, 0);
		
		mCollectionHotLineContentContentTitle = inState.getString(DATA_COLLECTION_HOTLINE_CONTENT_CONTENT_TITLE);
		mCollectionHotLineContentContent = inState.getString(DATA_COLLECTION_HOTLINE_CONTENT_CONTENT);
		loadCollectionHotLineDetail(true, 0); // 0 is meaningless
		
		mCollectionSceneSpotTitle = inState.getString(DATA_COLLECTION_SCENE_SPOT_TITLE);
		mCollectionSceneSpotImage = inState.getString(DATA_COLLECTION_SCENE_SPOT_IMAGE);
		mCollectionSceneSpotContent = inState.getString(DATA_COLLECTION_SCENE_SPOT_CONTENT);
		loadCollectionSceneSpot(true, 0); // 0 is meaningless
	}

	private void showCollectionContentView(int index) {
		for (int i = 0; i < mCollectionViews.length; i++) {
			mCollectionViews[i].setVisibility(View.GONE);
		}
		mCollectionViews[index].setVisibility(View.VISIBLE);
	}
	
	private void setCurrentCollectionContentView(int viewId) {
		mCollectionPageIndex = viewId;
		showCollectionContentView(mCollectionPageIndex);
	}
	
	/*
		Return true, database is not empty. use latest data to update the UI.
		Return false, database is empty, we need to update UI. That means display nothing)
	*/
	private boolean getCollectionFromDB() {
		String data[][] = mDatabase.getCollectionFromDB();
		if (data == null)
			return false; 
		int count = data[0].length;

		mCollectionListIds = new String[count];
		mCollectionListTitles = new String[count];
		mCollectionListTypes = new String[count];
		mCollectionListMainTypes = new String[count];
		
		for (int i = 0; i < count; i++) {
			String infoString = "";
			mCollectionListIds[i] = data[0][i];			
			mCollectionListTypes[i] = data[2][i];			
			mCollectionListMainTypes[i] = data[3][i];

			int mainType = Integer.parseInt(data[3][i]);
			
			if (mainType == SCENE_AREA_COLLECTION) {
				infoString += getResources().getString(R.string.scene_collection);
			} else if (mainType == NOTE_COLLECTION) {
				if (mCollectionListTypes[i].equals("0")) // 0 means 游记， 1 means 攻略
					infoString += getResources().getString(R.string.note_collection_travel);
				else
					infoString += getResources().getString(R.string.note_collection_strategy);
			} else if (mainType == INFO_COLLECTION) {
				infoString += getResources().getString(R.string.info_collection);
			} else if (mainType == SCENE_SPOT_COLLECTION) {
				infoString += getResources().getString(R.string.scene_spot_collection);
			}
			infoString += data[1][i];
			mCollectionListTitles[i] = infoString;
		}
		return true;
	}

    private void loadCollectionPage(Bundle inState) {
		mCollectionViews[NOTE_COLLECTION] = (View) findViewById(R.id.collection_note_content_id);
		mCollectionViews[COLLECTION_LIST] = (View) findViewById(R.id.collection_list_page_id);
		mCollectionViews[SCENE_AREA_COLLECTION] = (View) findViewById(R.id.collection_scene_id);
		mCollectionViews[SCENE_SPOT_COLLECTION] = (View) findViewById(R.id.collection_scene_spot_id);
		mCollectionViews[INFO_COLLECTION] = (View) findViewById(R.id.collection_hotline_content_scroll_id);

		if (inState == null) {
			displayCollectionListPage();
		} else {
			restoreCollectionPage(inState);
		}
    }

	private void loadCollectionListPage() {
        final ListView collectionListView = (ListView) findViewById(R.id.collection_list_id);
		boolean ret = getCollectionFromDB();
		if (!ret) {
        	collectionListView.setAdapter(null);
			return;
		}

		if (mCollectionListTitles != null && mCollectionListTitles.length > 0) {
        	collectionListView.setAdapter(new ArrayAdapter<String>(this, 
				android.R.layout.simple_list_item_1, mCollectionListTitles));
		}
		
		collectionListView.setOnItemLongClickListener(
			new AdapterView.OnItemLongClickListener() {
				public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
					final int pos = position;
					
					new AlertDialog.Builder(SearchActivity.this)
		            .setTitle(R.string.remove_collection_item_info)
		            .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
		                public void onClick(DialogInterface dialog, int whichButton) {		                	
		                	String id = mCollectionListIds[pos];
		            		int subType = Integer.parseInt(mCollectionListTypes[pos]);
		            		int mainType = Integer.parseInt(mCollectionListMainTypes[pos]);
		            		
		            		// remove related data in database and refresh UI
		                	mDatabase.deleteCollectionFromDB(id, subType, mainType);
		                	loadCollectionListPage();
		                }
		            }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
		                public void onClick(DialogInterface dialog, int whichButton) {
		                }
		            }).show();
					
					return true;
				}
			});
		
		collectionListView.setOnItemClickListener(
			new AdapterView.OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View view, int position,
		                    long id) {					
					/*
					 * 出现无法连接网络时， 应不应进入结果页面
					 */
					if (!HttpUtil.getNetworkStatus(MONTH_RECOMMEND)) {
	            		Toast.makeText(SearchActivity.this, getResources().getString(R.string.error_network), Toast.LENGTH_SHORT).show();
	            		return;
	            	}
					
					if (mCollectionListMainTypes != null) {
						int type = Integer.parseInt(mCollectionListMainTypes[position]);
						switch (type) {
						case SCENE_AREA_COLLECTION:
							loadCollectonSceneArea(position);
							setCurrentCollectionContentView(SCENE_AREA_COLLECTION);
							break;
						case NOTE_COLLECTION:
							loadCollectionNoteContent(false, position);
							setCurrentCollectionContentView(NOTE_COLLECTION);
							break;
						case INFO_COLLECTION:
							loadCollectionHotLineDetail(false, position);
							setCurrentCollectionContentView(INFO_COLLECTION);
							break;
						case SCENE_SPOT_COLLECTION:
							loadCollectionSceneSpot(false, position);
							setCurrentCollectionContentView(SCENE_SPOT_COLLECTION);
							break;
						}
		            	}
					}
		        });
	}
	
	private String createCollectionSceneAreaRequestUrl(int position) {
		return BASE_URL + PREFIX_SCENE_AREA_ID + mCollectionListIds[position] + PREFIX_SCENE_AREA_FLAG;
	}
	
	// collection page content
	private Handler mCollectonSceneAreaHandler;
	private static final int MSG_COLLECTION_SCENE_AREA = 0;
	private static final String KEY_MSG_COLLECTION_SCENE_AREA = "key_msg_collectioin_scene_area";

	private void loadCollectonSceneArea(int position) {
        //final String dest = getResources().getString(R.string.url1);
        //final HashMap<String, String> map = HttpUtil.parseSceneArea(HttpUtil.getJSONObject(dest));
		//String url = "http://nokia.hz.lotour.com/ScenicDetailForLenovo.ashx?id=1031&flag=0";
		String urlCollectionSceneArea = createCollectionSceneAreaRequestUrl(position);
		
		mCollectonSceneAreaHandler = new Handler() {
			public void handleMessage(Message msg) {
				switch(msg.what) {
				case MSG_COLLECTION_SCENE_AREA:
					String objStr = msg.getData().getString(KEY_MSG_COLLECTION_SCENE_AREA);
					JSONObject obj = HttpUtil.getJSONObject(objStr);
					mCollectionSceneAreaDetail = HttpUtil.parseSceneArea(obj, SearchActivity.this);
					if (mCollectionSceneAreaDetail == null)
						break;
					displayCollectionSceneAreaDetail();
					break;
				}
			}
		};
		
		int msgTypes[] = { MSG_COLLECTION_SCENE_AREA };
		String msgKeys[] = { KEY_MSG_COLLECTION_SCENE_AREA };
		mLoadingTask = new DataLoadingTask(mCollectonSceneAreaHandler, msgTypes, msgKeys).execute(urlCollectionSceneArea);
	}
	
	private void displayCollectionSceneAreaDetail() {
		TextView title = (TextView) findViewById(R.id.collection_scene_content_title_id);
		ImageView image = (ImageView) findViewById(R.id.collection_scene_content_image_id);
		TextView content = (TextView) findViewById(R.id.collection_scene_content_content_id);

		if (mCollectionSceneAreaDetail == null) {
			return;
		}
		
		String buffer[] = mCollectionSceneAreaDetail;
		if (!buffer[0].equals(NULL)) {
			title.setText(buffer[0]);
		}

		if (!buffer[1].equals(NULL)) {
			content.setText(buffer[1]);
			content.setVisibility(View.VISIBLE);
		} else {
			content.setVisibility(View.GONE);
		}
		
		View ticketRowView = (View) findViewById(R.id.collection_scene_content_ticket_row);
		if (!buffer[5].equals(NULL)) {
			TextView v = (TextView) findViewById(R.id.collection_scene_content_ticket);
			v.setText(buffer[5]);
			ticketRowView.setVisibility(View.VISIBLE);
		} else {
			ticketRowView.setVisibility(View.GONE);
		}
		View opentimeRowView = (View) findViewById(R.id.collection_scene_content_opentime_row);
		if (!buffer[4].equals(NULL)) {
			TextView v = (TextView) findViewById(R.id.collection_scene_content_opentime);
			v.setText(buffer[4]);
			opentimeRowView.setVisibility(View.VISIBLE);
		} else {
			opentimeRowView.setVisibility(View.GONE);
		}
		View phoneRowView = (View) findViewById(R.id.collection_scene_content_phone_row);
		if (!buffer[7].equals(NULL)) {
			TextView v = (TextView) findViewById(R.id.collection_scene_content_phone);
			v.setText(buffer[7]);						
			phoneRowView.setVisibility(View.VISIBLE);
		} else {
			phoneRowView.setVisibility(View.GONE);
		}
		View addressRowView = (View) findViewById(R.id.collection_scene_content_address_row);
		if (!buffer[6].equals(NULL)) {
			TextView v = (TextView) findViewById(R.id.collection_scene_content_address);
			v.setText(buffer[6]);						
			addressRowView.setVisibility(View.VISIBLE);
		} else {
			addressRowView.setVisibility(View.GONE);
		}
		View ratingRowView = (View) findViewById(R.id.collection_scene_content_rating_row);
		if (!buffer[2].equals(NULL)) {
			TextView v = (TextView) findViewById(R.id.collection_scene_content_rating);
			v.setText(buffer[2]);						
			ratingRowView.setVisibility(View.VISIBLE);
		} else {
			ratingRowView.setVisibility(View.GONE);
		}
		View typeRowView = (View) findViewById(R.id.collection_scene_content_type_row);
		if (!buffer[3].equals(NULL)) {
			TextView v = (TextView) findViewById(R.id.collection_scene_content_type);
			v.setText(buffer[3]);						
			typeRowView.setVisibility(View.VISIBLE);
		} else {
			typeRowView.setVisibility(View.GONE);
		}
		
		if (!buffer[8].equals(NULL)) {
			loadImageFile(buffer[8], image);
			image.setVisibility(View.VISIBLE);
		} else {
			image.setVisibility(View.GONE);
		}
	}
	
	private String createCollectionNoteContentRequestUrl(int position) {
		return BASE_URL + PREFIX_NOTE_CONTENT_ID + mCollectionListIds[position] 
			+ PREFIX_NOTE_CONTENT_FLAG + mCollectionListTypes[position];
	}
	
	private Handler mCollectionNoteContentHandler;
	private static final int MSG_COLLECTION_NOTE_CONTENT = 0;
	private static final String KEY_MSG_COLLECTION_NOTE_CONTENT = "key_msg_collection_note_content";
	
	private void loadCollectionNoteContent(boolean ready, int position) {
        //final String dest = getResources().getString(R.string.url5);
        //final HashMap<String, String> map = HttpUtil.parseNoteContent(HttpUtil.getJSONObject(dest), this);
        //String url = "http://nokia.hz.lotour.com/TravelsDetailForlenvo.ashx?id=1043&flag=0";
		if (!ready) {
			String urlCollectionNoteContent = createCollectionNoteContentRequestUrl(position);
			mCollectionNoteContentHandler = new Handler() {
				public void handleMessage(Message msg) {
					switch(msg.what) {
					case MSG_COLLECTION_NOTE_CONTENT:
						String objStr = msg.getData().getString(KEY_MSG_COLLECTION_NOTE_CONTENT);
						JSONObject obj = HttpUtil.getJSONObject(objStr);
						final HashMap<String, String> map = HttpUtil.parseNoteContent(obj, SearchActivity.this);
						if (map == null)
							break;

						mCollectionNoteContentTitle = map.get(HttpUtil.TITLE);
						mCollectionNoteContentContent = map.get(HttpUtil.CONTENT);
						mCollectionNoteContentAuthor = map.get(HttpUtil.USERNAME);
						displayCollectionNoteContent();
						break;
					}
				}
			};
			
			int msgTypes[] = { MSG_COLLECTION_NOTE_CONTENT };
			String msgKeys[] = { KEY_MSG_COLLECTION_NOTE_CONTENT };
			mLoadingTask = new DataLoadingTask(mCollectionNoteContentHandler, msgTypes, msgKeys).execute(urlCollectionNoteContent);
			
		} else {
			displayCollectionNoteContent();
		}
	}
	
	private void displayCollectionNoteContent() {
		TextView title = (TextView) findViewById(R.id.collection_note_content_title_id);
		TextView author = (TextView) findViewById(R.id.collection_note_content_author_id);
		TextView content = (TextView) findViewById(R.id.collection_note_content_content_id);
	
		title.setText(mCollectionNoteContentTitle);
		content.setText(mCollectionNoteContentContent);
		author.setText(mCollectionNoteContentAuthor);
	}
	
	private String createCollectionPrefixHotLineDetailRequestUrl(int position) {
		return BASE_URL + PREFIX_HOTLINE_DETAIL + mCollectionListIds[position];
	}
	
	private Handler mCollectionHotLineDetailHandler;
	private static final int MSG_COLLECTION_HOTLINE_DETAIL = 0;
	private static final String KEY_MSG_COLLECTION_HOTLINE_DETAIL = "key_msg_collection_hotline_detail";
	
	private void loadCollectionHotLineDetail(boolean ready, int position) {
		if (!ready) {
			//String url = "http://nokia.hz.lotour.com/NewsDetailForLenvo.ashx?id=359093";
			String urlCollectionHotlineDetail = createCollectionPrefixHotLineDetailRequestUrl(position);
			mCollectionHotLineDetailHandler = new Handler() {
				public void handleMessage(Message msg) {
					switch(msg.what) {
					case MSG_COLLECTION_HOTLINE_DETAIL:
						String objStr = msg.getData().getString(KEY_MSG_COLLECTION_HOTLINE_DETAIL);
						String buffer[] = splitTitleAndContent(objStr);

				        final HashMap<String, String> map = HttpUtil.parseHotLineContent(HttpUtil.getJSONObject(buffer[0]), SearchActivity.this);
						if (map == null)
							break;
				        mCollectionHotLineContentContentTitle = map.get(HttpUtil.TITLE);
						mCollectionHotLineContentContent = buffer[1];
						displayCollectionHotLineDetail();
						break;
					}
				}
			};
			
			int msgTypes[] = { MSG_COLLECTION_HOTLINE_DETAIL };
			String msgKeys[] = { KEY_MSG_COLLECTION_HOTLINE_DETAIL };
			mLoadingTask = new DataLoadingTask(mCollectionHotLineDetailHandler, msgTypes, msgKeys).execute(urlCollectionHotlineDetail);
			
			/*String dest = HttpUtil.getResponseString(url);
			String buffer[] = splitTitleAndContent(dest);

	        final HashMap<String, String> map = HttpUtil.parseHotLineContent(HttpUtil.getJSONObject(buffer[0]), this);
			mCollectionHotLineContentContentTitle = map.get(HttpUtil.TITLE);
			mCollectionHotLineContentContent = buffer[1];
			displayCollectionHotLineDetail();*/
			
		} else {
			displayCollectionHotLineDetail();
		}
	}
	
	void displayCollectionHotLineDetail() {
		final String mimeType = "text/html";
        final String encoding = "utf-8";

		TextView title = (TextView) findViewById(R.id.collection_hotline_content_title_id);
		WebView content = (WebView) findViewById(R.id.collection_hotline_content_content_id);

        title.setText(mCollectionHotLineContentContentTitle);
		content.loadData(mCollectionHotLineContentContent, mimeType, encoding);
	}
	
	private String createCollectoinSceneSpotRequestUrl(int position) {
		return BASE_URL + PREFIX_SCENE_SPOT_ID + mCollectionListIds[position] + PREFIX_SCENE_SPOT_FLAG;
	}

	private Handler mCollectionSceneSpotHandler;
	private static final int MSG_COLLECTION_SCENE_SPOT = 0;
	private static final String KEY_MSG_COLLECTION_SCENE_SPOT = "key_msg_collection_scene_spot";
	
	private void loadCollectionSceneSpot(boolean ready, int position) {
        //final String dest = getResources().getString(R.string.url4);
        //final HashMap<String, String> map = HttpUtil.parseScentSpot(HttpUtil.getJSONObject(dest), this);

		if (!ready) {
			String urlCollectionSceneSpot = createCollectoinSceneSpotRequestUrl(position);
			mCollectionSceneSpotHandler = new Handler() {
				public void handleMessage(Message msg) {
					switch(msg.what) {
					case MSG_COLLECTION_SCENE_SPOT:
						String objStr = msg.getData().getString(KEY_MSG_COLLECTION_SCENE_SPOT);
						JSONObject obj = HttpUtil.getJSONObject(objStr);						
						final HashMap<String, String> map = HttpUtil.parseScentSpot(obj, SearchActivity.this);
						if (map == null)
							break;
						mCollectionSceneSpotTitle = map.get(HttpUtil.TITLE);
						mCollectionSceneSpotImage = map.get(HttpUtil.IMAGE);
						mCollectionSceneSpotContent = map.get(HttpUtil.CONTENT);
						displayCollectionSceneSpot();
						break;
					}
				}
			};
			
			int msgTypes[] = { MSG_COLLECTION_SCENE_SPOT };
			String msgKeys[] = { KEY_MSG_COLLECTION_SCENE_SPOT };
			mLoadingTask = new DataLoadingTask(mCollectionSceneSpotHandler, msgTypes, msgKeys).execute(urlCollectionSceneSpot);

		} else {
			displayCollectionSceneSpot();
		}
	}
	
	private void displayCollectionSceneSpot() {
		TextView title = (TextView) findViewById(R.id.collection_scene_spot_content_title_id);
		ImageView image = (ImageView) findViewById(R.id.collection_scene_spot_content_image_id);
		TextView content = (TextView) findViewById(R.id.collection_scene_spot_content_content_id);
		
		title.setText(mCollectionSceneSpotTitle);
		content.setText(mCollectionSceneSpotContent);
		if (!image.equals(NULL)) {
			loadImageFile(mCollectionSceneSpotImage, image);
			image.setVisibility(View.VISIBLE);
		} else {
			image.setVisibility(View.GONE);
		}
		
	}
	
}
